Sign in to follow this  
fitfool

Detecting a TCP Disconnect

Recommended Posts

fitfool    113
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

Share this post


Link to post
Share on other sites
Codeka    1239
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.

Share this post


Link to post
Share on other sites
gz-    122
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.

Share this post


Link to post
Share on other sites
DrHalan    122
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this