c# detecting tcp disconnect

我的梦境 提交于 2019-11-28 20:53:49
Hermit Dave

TcpClient / NetworkStream does not get notified when the connection is closed. The only option available to you is to catch exceptions when writing to the stream.

A few years back we moved to using sockets instead of tcp client. socket is more usable as compared to tcpclient.

there are a couple of methods that you can use

Poll is one of them

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.poll.aspx

You can also do a check on outcome of Write itself. it gives you the number of bytes actually written.

The Connected property itself only reflects the state at the last operation. Its documentation states "The value of the Connected property reflects the state of the connection as of the most recent operation. If you need to determine the current state of the connection, make a non-blocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected."

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx

networkStream.DataAvailable

This property doesn't notify you if the socket is closed on the server side.

In your situation, you can either implement a "keepalive" function where you poll the connection every t minutes/seconds, or add lots of try/catches whenever you try to read or write from the socket. When I use TCP, i just include a Reconnect() method that goes into every catch statement.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!