Gregory Fedor <firstname.lastname@example.org> writes:
Having established a TCP/IP socket with a server, what is the best way
of determining if the connection has been lost (broken cable, server
crash, etc.)? Data is only being written to the socket by the client
and there is no feedback from the server via confirmation messages or
You’ll have to play with this, but I’m sure that writing to the socket
will generate an error once the socket is closed. If you are using
non-blocking writes, then you have to check errno to ensure that the
error is not EWOULDBLOCK, as that is really a status return, not an
Similarly, how about the situation where a server is sending data to a
client. Can the client detect the connection has been broken? (yes I
now the data will stop, but it may do that in the course of normal
peration so it’s not a good indicator)
Typically the client waits for data on a select() call. The select()
only returns when there is an event on one of the file descriptors in
the fdset. If the particular fd has an event, and reading it
generates 0 bytes of data, then the socket has closed. This will not
work if you fd is connected to a terminal device in “cooked” mode.
Note that socket timeouts are generally very long. If you cut the
cable between two computers talking TCP/IP, the timeout will take
betwen 5 and 15 minutes.
Andrew Thomas, President, Cogent Real-Time Systems Inc.
2430 Meadowpine Boulevard, Suite 105, Mississauga, Ontario, Canada L5N 6S2
Email: email@example.com WWW: http://www.cogent.ca