gpt4 book ai didi

c - 写入和读取 - 套接字 AF_UNIX

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:30 24 4
gpt4 key购买 nike

我正在为大学做一个项目。需要编写一个套接字的代码,一个服务器和一个客户端通过这个套接字进行通话。消息是这样的:

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;
}

这是发送消息

/** 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 的 INVALID ARGUMENT 并且套接字中没有写入和读取消息,我认为问题出在缓冲区的长度(无符号整数)有什么建议吗?

最佳答案

查看联机帮助页以了解有关 EINVAL 的内容,您要么发送了无效的套接字,要么发送了无效的 read() 指针。尝试调试您的哪个 read() 调用也失败了。

但是这是错误的:

lung = read(sc, &(msg->buffer), sizeof(char)*msg->length);

你的缓冲区是一个指针,你想读取它指向的任何地方的数据,而不是它的地址。所以应该是

lung = read(sc, msg->buffer, sizeof(char)*msg->length);

关于c - 写入和读取 - 套接字 AF_UNIX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20644424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com