Detecting a TCP Disconnect

Started by
4 comments, last by fitfool 15 years, 4 months ago
Well i know you can detect a disconnection by checking the return value of recv(), but this poses some problems. I'm trying to write an isConnected() method for my TCP socket-wrapper-class, but i can not effectively tell if the socket has disconnected when there is still data ready to be recv'd(). Is there any other way? I guess a could just read all the data, and check recv() returns 0 in any of the calls, and then somehow re-insert it onto the TCP stack/queue/whatever, but, is there a better way? thanks
Advertisement
Quote:Original post by fitfool
Well i know you can detect a disconnection by checking the return value of recv(), but this poses some problems. I'm trying to write an isConnected() method for my TCP socket-wrapper-class, but i can not effectively tell if the socket has disconnected when there is still data ready to be recv'd(). Is there any other way? I guess a could just read all the data, and check recv() returns 0 in any of the calls, and then somehow re-insert it onto the TCP stack/queue/whatever, but, is there a better way? thanks


You cannot know the other side has disconnected until you read the rest of the buffer. That's just the way TCP works.

In any case, an "isConnected" method wouldn't really make sense. After all, if you call it at it returns "isConnected", the client could disconnect before you do anything else, you just don't know.

try figure on time out recv/send.

Yea I'll periodically send a 'keepalive' packet if the connection is quiet and if the send fails then it's considered disconnected. I know in the background TCP is sending keepalive's but the default timeout period is something like 2 hours and I'm not sure if there's a way to get a callback to tell you that the connection has been dropped. But that's my hacky way of doing it.
well in my framework i use select() if select tells me that the socket is readable but recv returs the lenght 0 i know it is a disconnect.

Just chekc out my code and copy whatever you need it is zlib licensed :) http://code.google.com/p/open-network/source/browse/#svn/trunk
My Blog - http://www.freakybytes.org
Thanks for the replys, i've figured out a decent way of doing it.

This topic is closed to new replies.

Advertisement