Excuse the naivete of the question, but what is the right way to determine if a socket connection is still good? Of course, if I try to send or receive data on a bad connection, the call will fail, but is there a way to check the state of a connection without necessarily trying to send or receive data?
Consider the following example. Say I have a client that connects to a server, and the server periodically sends data to the client. In between sends, the server does some work. How can the server know if the client has disconnected, without sending the client any data? In other words, is there anyway that the server can test the connection while it is still doing work, so that if the client were to disconnect, it would immediately know it and not later on when it tried to send data. Obviously, I don't want to impose some kind of ping or ack in the protocol between the client and the server.
I've looked into using select() but I am not sure that this fits the bill.
I have done some testing however, and I've come up with the following. The server can "test" the connection by periodically sending 0 bytes to the client. In my testing of this idea, I've found that the server will immediately detect the client disconnection the next time it sends 0 bytes to the client. Also, the client doesn't seem to "notice" the 0 bytes sent to it. In other words, sending 0 bytes doesn't seem to cause a problem.
The advantage of my scheme seems to be (1) it's very simple, (2) it doesn't require any kind of ping or ack protocol between the client and the server and (3) it's very simple! :) However, I'm sure that there's probably a better way to do it...