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

前端 未结 11 1210
礼貌的吻别
礼貌的吻别 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条回答
  •  Happy的楠姐
    2020-11-28 19:00

    The best way is simply to have your client send a PING every X seconds, and for the server to assume it is disconnected after not having received one for a while.

    I encountered the same issue as you when using sockets, and this was the only way I could do it. The socket.connected property was never correct.

    In the end though, I switched to using WCF because it was far more reliable than sockets.

提交回复
热议问题