Knowning when a NetworkStream is closed

1.7k views Asked by At

I'm writing tcp server and client applications. How can the server know when the connection to the client is not available, like when the client's computer suddenly crashed and no FIN flag sent?

When I try to write to the network stream it throws me an exception, I want to know how can I catch this exception without reading from / writing to the stream or another way to know if the stream is closed.

any help?

2

There are 2 answers

1
Fortune On

You can't, there's no way to check if the connection is close without catching an exception.

Attempting to write/read on the client will throw an exception which mean the connection is closed.

0
dvasanth On

TCP has keep alive interval where keep alive probe packets are used to check whether the other party is still alive. You need to check the SO_KEEPALIVE socket option for more information. Another better option is to have the probe packets send at the application layer at regular intervals. You can set TCP receive timeout at server end to some nominal value say 1 minute. From the client end you can send dummy request every minute. If there is no request received within this time, server recv will timeout and its assumed the client connection is lost.