How do i check if TcpClient is connected?

馋奶兔 提交于 2019-12-24 01:46:13

问题


When my client app closes the socket or even terminates my server still thinks its alive. I even check TcpClient.Connected then i see this. I bolded the important part

true if the Client socket was connected to a remote resource as of the most recent operation; otherwise, false.

How do i know if the socket is closed or not? At the moment I have to do an operation and get an exception to discover if its opened or close


回答1:


There are so many things that can break communications over a socket, many of which are totally outside your control, best keep it simple.

At the moment you have a perfectly acceptable detection mechanism, dead simple and low cost.

You could do a heart beat, send an I'm here message from the client every X somethings, and then have the server run through and see if there hadn't been one for X * fiddle factor intervals. Uses processor time and bandwidth though.

Another option depends on your client detecting it's no longer connected and requesting a new connection. If you have a unique identifier in the request , you can run through your existing connections for it, kill it, if it's there, and start then continue as normal.

I know exception doesn't feel right, but it's only really a problem if you keep losing the connection, and if you were your efforts would be better directed at sorting that out.



来源:https://stackoverflow.com/questions/12117373/how-do-i-check-if-tcpclient-is-connected

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