Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket programming issue with recv() receiving partial messages

Tags:

c

linux

I have a socket that is receiving streaming stock tick data. However, I seem to get a lot of truncated messages, or what appears to be truncated messages. Here is how I am receiving data:

if((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
    perror("recv()");
    exit(1);
}
else {
    buf[numbytes] = '\0';
    // Process data
}

Can recv() receive just a partial message of what was sent?

My feeling is I might need another loop around the recv() call that receives until a complete message is sent. I know that a libcurl implementation I have (not possible to use libcurl here I would think) has an outer loop:

// Read the response (sum total bytes read in tot_bytes)
for(tot_bytes=0; ; tot_bytes += iolen)
{  
    wait_on_socket(sockfd, 1, 60000L);
    res = curl_easy_recv(curl, buf + tot_bytes, sizeof_buf - tot_bytes, &iolen);

    if(CURLE_OK != res) {
        // printf( "## %d", res );
        break;
    }
}

Do I need an recv() loop similar to the libcurl example (that verifiably works)?

like image 626
Don Wool Avatar asked Apr 20 '12 17:04

Don Wool


1 Answers

We can also pass the flag to recv to wait until all the message has arrived. It works when you know the number of bytes to receive. You can pass the command like this.

numbytes =  recv(sockfd, buf, MAXDATASIZE-1, MSG_WAITALL);
like image 71
Anshuman Avatar answered Oct 20 '22 22:10

Anshuman