How to check if a socket is connected/disconnected in C#?(如何在 C# 中检查套接字是否连接/断开连接?)
问题描述
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 disconnected ungracefully)?
As Paul Turner answered Socket.Connected
cannot be used in this situation. You need to poll connection every time to see if connection is still active. This is code I used:
bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
It works like this:
s.Poll
returns true if- connection is closed, reset, terminated or pending (meaning no active connection)
- connection is active and there is data available for reading
s.Available
returns number of bytes available for reading- if both are true:
- there is no data available to read so connection is not active
这篇关于如何在 C# 中检查套接字是否连接/断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!