为什么socket recv会在while循环中不断接收数据,即使我没有从发件人发送任何数据 [英] why socket recv keeps receiving data in a while loop, even if I don't send any data from sender
问题描述
问题: 1.为什么即使我不从发送方发送任何数据,socket recv仍会在while循环中继续接收数据?不是recv()的阻塞函数,我以为它会阻塞直到tcp接收到一些数据为止; 2.为什么numbytes = 0?
Questions: 1. why socket recv keeps receiving data in a while loop, even if I don't send any data from sender? isn't recv() a blocking function, I thought it blocks until tcp receives some data; 2. why numbytes = 0 ?
下面是代码,我只发布了recv()和send()的代码,我认为代码的其他部分都可以正常工作,但是如果您需要所有代码进行调试,请告诉我,我将发布它们,谢谢!
Below is the code, I just post the code of recv() and send(), I think other parts of the code works fine, but if you need all code to debug, please let me know I'll post them, Thanks!
while(1) { //client receiving code
if ((numbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
perror("recv");
}
buf[numbytes] = '\0';
printf("numbytes is %d\n", numbytes);
printf("client: received '%s'\n", buf);
}
while(1) { //server sending code
char str[100];
sin_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
if (new_fd == -1) {
perror("accept");
continue;
}
inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
printf("server: got connection from %s\n", s);
while(1) {
printf( "Enter a value :");
scanf("%s", str);
if (send(new_fd, str, 50, 0) == -1)
perror("send");
}
}
以下是结果的屏幕截图: 在服务器终端上输入
Below is the screenshot of the result: Input on the server terminal
Enter a value :123456
客户终端上的输出
numbytes is 0
client: received '12345'
numbytes is 0
client: received '6'
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
numbytes is 0
client: received ''
推荐答案
因为您忽略了recv()
返回零的可能性,这意味着对等方已经关闭了连接,这意味着您也必须这样做,并停止阅读.
Because you're ignoring the possibility of a zero return from recv()
, which means the peer has closed the connection, which means you must do so too, and stop reading.
这篇关于为什么socket recv会在while循环中不断接收数据,即使我没有从发件人发送任何数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!