为什么 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 循环中接收数据,即使我没有从 sender 发送任何数据? recv() 不是阻塞函数,我认为它会阻塞直到 tcp 收到一些数据; 2. 为什么 numbytes = 0 ?

下面是代码,我只是 post recv() 和 send() 的代码,我认为代码的其他部分可以正常工作,但是如果您需要调试所有代码,请让我知道我会 post 他们,谢谢!

 while(1) { //client receiving code
        if ((numbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
            perror("recv");
        }
        buf[numbytes] = '[=10=]'; 
        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");
        }
    }

结果截图如下: 服务器端输入

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() 的零 return 的可能性,这意味着对等方已关闭连接,这意味着你也必须这样做,并停止阅读。