-1

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 ''
qifan
  • 7
  • 1
  • 2

1 Answers1

1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks, I get it, but how come numbytes is always 0, even if the client received '12345'? – qifan Apr 19 '15 at 21:56
  • The client *didn't* receive `12345`. It received zero bytes, which means end of stream. The stuff in the buffer is just left over from before. – user207421 Apr 20 '15 at 00:26
  • Note that it's not possible for the client code to generate that output (because of the `buf[numbytes]='\0'`), so either that's not the real code, or it's not the real output. – user3386109 Apr 20 '15 at 01:04
  • @EJP so I should write a piece of code like this: if (numbytes == 0) {close(sockfd); break;}, then this condition can be avoid? – qifan Apr 20 '15 at 02:17
  • @UI_jjw Isn't that exactly what it says in my answer? – user207421 Apr 20 '15 at 21:47