gpt4 book ai didi

c - 无法使用套接字写入流

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

我是 C 的新手,在使用套接字写入流时遇到了问题。

我正在使用网络流/套接字尝试在两个方向上发送消息(从主机到客户端和客户端到主机)但是当我从客户端收到消息时它被加扰了(我猜是由于编码问题?)。

这是我的代码的相关部分:

host.c

int client_sock_fd;

int main(int argc, const char* argv[]) {
while (1) {
char input[80];
scanf("%s", input);
// send to client, transmitted fine
write(client_sock_fd, &input, sizeof(input));

char response[80];
read(client_sock_fd, &response, sizeof(response));
// Prints the missing character symbol, and 'random' letters
printf("Response: %s\n", response);
}
}

客户端.c

int host_sock_fd; // file descriptor for host

void writeResponse(

int main(int argc, const char* argv[]) {
while (1) {
char message[80];
// the message is transmitted fine
read(host_sock_fd, &message, sizeof(message));

writeResponse("Response message");
}
}

void writeResponse(char response[80]) {
write(host_sock_fd, &response, sizeof(response));
}

我不太确定如何继续。我知道如果我简单地在客户端写回接收到的消息它工作正常,那么这是每个字符的内存量的问题吗?

最佳答案

我在下面显示了缺乏知识,我不会删除它,但这是导致您在 writeResponse(char response[80]) 中出现问题的原因,因为 response 被视为 char * 而不是 char[80]。但一般来说,不要在不需要时使用 & ,它会像你的那样导致错误。将 char[] 视为 char * ,这是关于引用级别的,两者之间存在差异,但在这种情况下不是。

它的工作原理很奇怪,因为您将缓冲区声明为 char input[80]; 等,这些变量已经是 char 指针,您不应该将它们的地址传递为读/写函数的参数,所以它应该是:

write(client_sock_fd, input, sizeof(input)); 

代替:

write(client_sock_fd, &input, sizeof(input)); 

在所有读写情况下。 您可能想看看those examples

关于c - 无法使用套接字写入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769917/

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