简体   繁体   中英

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

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 ac# program do this?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM