根据 Socket.Poll 的文档:
此方法无法检测某些类型的连接问题,例如网络电缆损坏或远程主机被不正常关闭。您必须尝试发送或接收数据以检测此类错误。
换句话说 - 轮询对于检查某些数据是否到达以及是否可用于您的本地操作系统网络堆栈很有用。
如果您需要检测连接问题,您需要调用阻塞读取(例如Socket.Receive)
您还可以构建一个简单的初始化迷你协议来来回交换一些约定的“你好”消息。
这是一个简化的示例:
private bool VerifyConnection(Socket socket)
{
byte[] b = new byte[1];
try
{
if (socket.Receive(b, 0, 1, SocketFlags.None) == 0)
throw new SocketException(System.Convert.ToInt32(SocketError.ConnectionReset));
socket.NoDelay = true;
socket.Send(new byte[1] { SocketHelper.HelloByte });
socket.NoDelay = false;
}
catch (Exception e)
{
this._logger.LogException(LogLevel.Fatal, e, "Attempt to connect (from: [{0}]), but encountered error during reading initialization message", socket.RemoteEndPoint);
socket.TryCloseSocket(this._logger);
return false;
}
if (b[0] != SocketHelper.HelloByte)
{
this._logger.Log(LogLevel.Fatal,
"Attempt to connect (from: [{0}]), but incorrect initialization byte sent: [{1}], Ignoring the attempt",
socket.RemoteEndPoint, b[0]);
socket.TryCloseSocket(this._logger);
return false;
}
return true;
}