How to check if a socket is connected/disconnected in C#?

前端 未结 11 1236
礼貌的吻别
礼貌的吻别 2020-11-28 18:50

How can you check if a network socket (System.Net.Sockets.Socket) is still connected if the other host doesn\'t send you a packet when it disconnects (e.g. because it discon

11条回答
  •  一个人的身影
    2020-11-28 19:25

    The Socket.Connected property will tell you whether a socket thinks it's connected. It actually reflects the status of the last send/receive operation performed on the socket.

    If the socket has been closed by your own actions (disposing the socket, calling methods to disconnect), Socket.Connected will return false. If the socket has been disconnected by other means, the property will return true until you next attempt to send or recieve information, at which point either a SocketException or ObjectDisposedException will be thrown.

    You can check the property after the exception has occurred, but it's not reliable before.

提交回复
热议问题