I have a server based on BSD sockets, with select
to detect events. It keeps closing connections when clients still have data to send (the clients throw Connection reset by peer).
This is my code on server side:
if (FD_ISSET(sd,&readfds)){//we have an event from select
int count=0;
ioctl(sd,FIONREAD,&count);//should return available data
if(count==0){
u_int8_t c;
count=recv(sd, &c, 1, MSG_PEEK);//this should just check if data available without reading
if(count==0)close(sd);
}
else if(count>expected_message_size)//do something
else //do nothing until enough data arrives
}
Google says that if recv returns 0, it means client closed socket, but it does not seem to work. As far as I know, it should not work, because recv/read returns the amount of data read, but we are dealing with internet communication here - what if there is no data right now, because we've read everything the client has sent so far, but there is more to come?
man recv actually says:
Datagram sockets in various domains (e.g., the UNIX and Internet domains) permit zero-length datagrams. When such a datagram is received, the return value is 0.
More searching led me to the MSG_PEEK method, but that did not help. What am I doing wrong?
I am on Linux, and do not need to support any other OS.