Search code examples
socketstcpnetwork-programmingblocking

why socket recv keeps receiving data in a while loop, even if I don't send any data from sender


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 ?

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

Output on the client terminal

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 ''

Solution

  • 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.