Knowning when a NetworkStream is closed

时间:2015-06-15 14:58:51

标签: c# tcp network-programming tcpclient tcplistener

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 个答案:

答案 0 :(得分:0)

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.

答案 1 :(得分:0)

TCP保持活动间隔,其中保持活动探测包用于检查对方是否仍然活着。您需要检查SO_KEEPALIVE套接字选项以获取更多信息。 另一个更好的选择是使探测包定期在应用层发送。您可以将服务器端的TCP接收超时设置为某个标称值,例如1分钟。从客户端,您可以每分钟发送虚拟请求。如果在此时间内没有收到请求,服务器recv将超时并假定客户端连接丢失。

相关问题