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

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

The value of the Connected property
reflects the state of the connection
as of the most recent operation. If
you need to determine the current
state of the connection,make a
nonblocking,zero-byte Send call. If
the call returns successfully or
throws a WAEWOULDBLOCK error code
(10035),then the socket is still
connected; otherwise,the socket is no
longer connected.

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

解决方法

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);
    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);

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...