gpt4 book ai didi

c - Recv 调用获取空数据

转载 作者:行者123 更新时间:2023-11-30 15:23:03 25 4
gpt4 key购买 nike

我正在学习使用 c 中的套接字。这是我的代码:

void work_with_client(int client_sock){
char buff[10] = {0};

while(1){
kv_log_message("\tWork with client\n");
int is_received = recv(client_sock, buff, 10, 0);
if(is_received < 0){
perror("Received failed");
} else {
printf("RESPONSE: %s\n", buff);
}
printf("RESPONSE %d\n", is_received);

sleep(1);
}
}

当我通过 telnet 连接到该服务器并立即断开连接时,服务器打印以下行:

    Work with client
RESPONSE:
RESPONSE 10
Work with client
RESPONSE:
RESPONSE 10
Work with client
RESPONSE:
RESPONSE 10
Work with client
RESPONSE:
RESPONSE 10
Work with client
RESPONSE:
RESPONSE 1
Work with client
RESPONSE:
RESPONSE 0
Work with client

而且我不明白为什么前 4 个 recv 调用会获取完整大小的缓冲区数据(从客户端角度来看,我没有向套接字写入任何内容)。有什么建议么?附:在 Mac OS X Yosemite 上运行

更新:我在 Linux 上测试我的程序,在我的情况下,recv 调用总是返回 0,所以可能是 Mac OS X 上 telnet 的问题

最佳答案

recv()返回0时,表示对方关闭了连接。

来自man recv :

RETURN VALUE

[...] The return value will be 0 when the peer has performed an orderly shutdown.

然后您可能想退出 while() 循环。

<小时/>

更新:

此外,代码还可能通过将非 0 终止的“字符串”传递给 printf() 来调用未定义的行为。

要解决此问题,请读取 buff 少一个 char,然后读取其大小并添加 0 终止符。

    while (1)
{
ssize_t is_received = recv(client_sock, buff, sizeof buff - 1, 0);
if (is_received < 0){
perror("Received failed");
break;
} else if (is_received == 0) {
printf("%s\n", "peer shutdown");
break;
}

buff[is_received] = '\0';
printf("RESPONSE: %s\n", buff);
}

关于c - Recv 调用获取空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28926298/

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