I have 2 machines running a simple C TCP server that I have written for testing purposes, 1 with Fedora 16, the other with Ubuntu 11.10. My Fedora machine works perfectly but on the Ubuntu machine, recv() does not block. Please keep in mind that these machines are running the same exact code. Has anybody seen this before? Thanks
int TcpSocket::ReadFromClient(int socket, char* buf, int len)
{
char *request = buf;
int slen = len;
int c = recv(socket, request, slen, 0);
while((c > 0) && (request[c-1] != '\n'))
{
request += c;
slen -= c;
c = recv(socket, request, slen, 0);
}
if (c < 0)
{
return c;
}
else if(c == 0)
{
//Sending back an empty string
buf[0] = '\0';
}
return len-slen;
}
It looks like the intention of your code is to stop reading when a
'\n'byte arrives. If that is the case then you need to read from the socket 1 byte at a time instead of using the entire available buffer size, especially since you are only checking the last byte of the buffer instead of checking every byte received.You should also change the loop logic to only call
recv()in one place instead of two places. Your current implementation is calling recv() withslen=0when the buffer is exhausted, which will setc=0and nullify the first byte in the buffer.Try this instead: