如何在C#中进行非阻塞套接字调用以确定连接状态?

Socket上的Connected属性的MSDN文档说明如下:

Connected属性的值反映了最近操作时的连接状态。 如果需要确定连接的当前状态,请进行非阻塞,零字节发送调用。 如果调用成功返回或抛出WAEWOULDBLOCK错误代码(10035),则套接字仍然连接; 否则,套接字不再连接。

我需要确定连接的当前状态 – 如何进行非阻塞,零字节发送调用?

Socket.Connected属性(至少.NET 3.5版本)的MSDN文档底部的示例显示了如何执行此操作:

// .Connect throws an exception if unsuccessful client.Connect(anEndPoint); // This is how you can determine whether a socket is still connected. bool blockingState = client.Blocking; try { byte [] tmp = new byte[1]; client.Blocking = false; client.Send(tmp, 0, 0); Console.WriteLine("Connected!"); } catch (SocketException e) { // 10035 == WSAEWOULDBLOCK if (e.NativeErrorCode.Equals(10035)) Console.WriteLine("Still Connected, but the Send would block"); else { Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode); } } finally { client.Blocking = blockingState; } Console.WriteLine("Connected: {0}", client.Connected); 

Socket.BeginSend

只是根据经验提供额外信息: Socket.Connect文档页面版本3.5和4底部的注释描述了我的经验 – 这个例子根本不起作用。 真的希望我知道它为什么适用于某些人而不是其他人。

作为解决方法,尽管文档说的是,我更改了示例以实际发送没有标志的1字节。 这成功更新了Connected属性的状态,相当于每隔一段时间发送一个keep-alive数据包。