How can I check whether a (TCP) socket is (dis)connected in C#?

后端 未结 4 999
南笙
南笙 2020-12-04 10:19

How should I check a (TCP) socket to find out whether it is connected?

I have read about the Socket.Connected property in MSDN, but it says it only show

4条回答
  •  星月不相逢
    2020-12-04 11:00

    Typically one would use the Socket.Select method to determine the state of a set of sockets (Socket.Poll for a single socket).

    Both of these methods allow you to query a socket's state. Now, assuming that you have tracked that the socket connected in the first place then you would typically call Select/Poll on the socket before attempting a read. If Select/Poll indicate that the socket is readable this tells you that:

    • Either the socket has data available top read in which case Receive will return the data available to read.
    • The socket socket has been closed, in which case when you call Receive 0 bytes will be returned immediately (i.e. If Select/Poll indicate that the socket is readable and you call Receive but it returns immediately with 0 bytes then you know that the connection has either been Closed, Reset or Terminated.

    Personally I've never used Poll - I've always used Select but MSDN seems to suggest that Poll is pretty much the same as Select but for single sockets.

    I'll also add that in most cases using Select is the most efficient and best way of handling Socket connections.

提交回复
热议问题