Advertisement

When a TCP connection closes...

Started by December 06, 2005 12:24 PM
3 comments, last by DIB 19 years, 2 months ago
Simple question: If you have a TCP client and server, the server "listens" for a client and then "connects" to that client. Is there any way, then, for the client and/or the server to detect if the other side closes the connection? A socket option or something? Thanks!
The only way I know of is if recv() returns 0 then the other side has closed the connection. For example, if you're using select(), when the TCP connection has been closed the socket will appear in the read set. When you try and read waiting data with recv(), it'll return 0 and you can handle the closed connection situation.
Advertisement
Ok, that is what I was doing right now, but that was just a little "dirty" for my taste. Thanks for the input!
Different socket APIs provide different notifications for socket events asynchronously, and there usually exists a notification for receiving the FIN message from the remote socket, but that only works if the connection is closed gracefully.

If the connection is broken in some other way (for example: a switch goes down) you are at the mercy of the tcp implimentation's timeout. The version I work with the most takes about 9 minutes to return a connection closed error in some circumstances.

In order to get quicker notification I have added a session management protocol on top of tcp. I would recommend doing the same.
Well, I learn something new every day...thanks!

This topic is closed to new replies.

Advertisement