0
我正在爲大學做一個項目。需要編寫一個套接字和一個服務器的代碼,以及一個談論這個套接字的客戶端。 Messagges像:寫和讀 - 套接字AF_UNIX
typedef struct {
/** message type */
char type;
/** message length in byte */
unsigned int length;
/** message buffer */
char *buffer;
} message_t;
我寫的Socket代碼和兩個函數現在我遇到的問題:和的sendMessage receiveMessage
/** read a message from the socket --- properly split the message and put it in the struct message_t
* \param sc file descriptor of the socket
* \param msg
*
* \retval lung length of the buffer read, if it's OK
* \retval -1 if there are errors (set errno)
*
*
*/
int receiveMessage(int sc, message_t * msg) {
int lung;
lung = read(sc, &(msg->type), sizeof(char));
if(lung == 0)
return -1;
if(lung == -1)
return -1;
lung = read(sc, &(msg->length), sizeof(unsigned int));
if(lung == 0)
return -1;
if(lung == -1)
return -1;
if(msg->length > 0) {
msg->buffer = malloc (sizeof(char)*msg->length);
lung = read(sc, &(msg->buffer), sizeof(char)*msg->length);
if(lung == 0)
return -1;
if(lung == -1)
return -1;
}
return lung;
}
這是的sendMessage
/** write a message on the socket --- should send only significant byte of the buffer (msg->length byte) -- must use only 1 write
* \param sc file descriptor of the socket
* \param msg address of the struct
*
* \retval n no. of char sent (if its OK)
* \retval -1 if there are errores (set errno)
*
*
*/
int sendMessage(int sc, message_t *msg) {
int n,lung;
lung = sizeof(unsigned int) + sizeof(char) + (sizeof(char)*msg->length);
record = malloc (lung);
sprintf(record,"%c%u%s",msg->type,msg->length,msg->buffer);
n = write(sc,record,lung);
if(n == 0)
return -1;
return n;
}
測試返回無效接收消息和沒有消息的ARGUMENT被寫入並在套接字中讀取,我認爲問題是與緩衝區的長度(一個無符號整數) 有什麼建議嗎?
'sprintf'格式化人類可讀的字符串,而不是數據到二進制緩衝區。因此,我認爲有一件事立即發現錯誤是你的緩衝區太小,因爲'msg-> length'可能比'sizeof(unsigned int)'大。 –
memcpy怎麼樣? – user2590319
'memcpy'會複製字節,但請記住'unsigned int'的大小和字節順序可能因平臺而異。你可以通過使用'stdint.h'中的大小類型來處理大小,你可以用'htonl'等函數來處理字節序。 –