我在为大学做一个项目。需要编写一个socket的代码,一个服务器和一个客户机在这个socket上讲话。消息如下:
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;
}
测试返回receiveMessage的无效参数,套接字中没有写入和读取消息,我认为问题在于缓冲区的长度(无符号int)
有什么建议吗?
最佳答案
请检查手册页上是否有关于EINVAL的内容,您发送的不是无效的套接字,就是指向read()的无效指针。尝试调试哪些read()调用也失败。
但这是错误的:
lung = read(sc, &(msg->buffer), sizeof(char)*msg->length);
你的缓冲区是一个指针,你想读取数据的任何地方,而不是它的地址。所以应该是
lung = read(sc, msg->buffer, sizeof(char)*msg->length);