Home > Blockchain >  Socket recv() receives only 1 byte of data
Socket recv() receives only 1 byte of data

Time:11-17

I was trying to send "-1" as an indicator from the server to the client using send() function, however the recv() function at the client side keeps receiving only 1 byte of the data (the return of recv() is 1).

Code

Server-side:

get_fd(buf, fd, stat_buf) gets a file descriptor based on the number in buf and returns -1 if the number in buf is invalid 0 if everything works fine.

if(get_fd(buf, fd, stat_buf) == -1){    // invalid file number
    printf("client has given an invalid file number\n\n");
    if(send(new_sockfd, "-1", 3, 0) == -1){
        perror("client: send");
    }

    close(new_sockfd);
    exit(1);

} else {    // valid file number
    /* code */
}

When I entered an invalid file number at the client-side, the printf() on the second line works fine and no perror() message has been seen.

Client-side:

std::memset(&buf, 0, MAXDATASIZE);    // clear the buffer for it has been used previously
if((numbyte = recv(sockfd, buf, MAXDATASIZE-1, 0))==-1){
    perror("client: recv");
    exit(1);
}

buf[numbyte] = '\0';
printf("numbyte: %d, received: %s\n\n", numbyte, buf);

The numbyte is always 1, while printf() prints nothing for the buf as string, but when printing the buf as an int (%d) it prints a nonsense negative number, for example -333179216.

CodePudding user response:

The problem was at the beginning of the connection when the server sends ( send() ) the first message to the client. You set the len to a number that is much larger than its actual length. It works fine in the beginning because there are no more communications, but the problem will appear when you try to send() through that socket again.

Code (integrity matters):

if(send(new_sockfd, "some words here...", 65535, 0) == -1){
    perror("server: send");
}
  • Related