Is it possible to detect if a socket is in the CLOSE_WAIT state?

情到浓时终转凉″ 提交于 2019-12-24 10:32:00

问题


I am using a TcpClient object to send and receive data. When a client loses its connection, I can see by using TcpView that its associated connection is in a CLOSE_WAIT state. Is it possible in c# to see the state of a socket? I simply want to detect the CLOSE_WAIT state so I can close the socket on the server end. I understand that I can wait to receive bytes for a certain amount of time and then close the connection if nothing is received. I just would rather close the socket and its thread immediately. Is the socket's state able to be detected on the c# side? The TcpView program can determine this. Can a c# program do this?


回答1:


It's not ideal, but if you check socket.Available, it'll throw a SocketException. You still need to check the reason, though.

Also not ideal, because it's a bit clunky, is to call Poll() (with SelectRead). If it returns true, either there's data to read or the connection is closed. If there's no data to read, then that's your answer.



来源:https://stackoverflow.com/questions/23665917/is-it-possible-to-detect-if-a-socket-is-in-the-close-wait-state

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