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'等函数来处理字节序。 –