TCPSocket Connection

I am working on a network application on an unstable network. I need to
do something like call client.connected?() on the server side to see if
the clients are still connected before I try to write to them. Any
ideas?

[email protected][email protected] writes:

I am working on a network application on an unstable network. I need to
do something like call client.connected?() on the server side to see if
the clients are still connected before I try to write to them. Any
ideas?

If the network is unstable, that means there could be instances where
a connection is disconnected improperly. This means, either end may
not know that the other has gone away.

There is no heart beat in TCP protocol (there actually is: the keep
alive packet, but 1. you can’t rely on that being enabled by the other
side, 2. the default interval is 2 hours, way too long for most
apps), so you can’t readily be informed of any disruption.

The only way to see if the other side has gone away is to try to
perform IO on the connection.

In the case of writing, you’ll get an exception if the other side has
gone away.

In the case of reading, if the connection was closed amicably, you’ll
get an end-of-stream (0-byte read), otherwise, it may just block
indefinitely.

Therefore, it is of utmost importance to always set some timeout when
trying to read because you can never know if the connection has became
invalid. In ruby, you can simply use the timeout library (require
‘timeout’).

YS.

I should have mentioned that this is only a one way write from the
server. So, what I am currently doing is trying to write to the client
and catching the exception if it is no longer connected. It just seems
a little kludgy to do that. And I wanted to get a feel for what other
people have done in this situation. Thanks.