问题
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