Socket 上 Connected 属性的 MSDN 文档说明如下:
Connected 属性的值
反映连接的状态
截至最近一次操作。如果
你需要确定当前
连接状态,进行
非阻塞、零字节发送调用。如果
调用成功返回或
抛出 WAEWOULDBLOCK 错误代码
(10035),那么套接字仍然是
连接的;否则,套接字没有
连接时间更长。
我需要确定连接的当前状态 - 如何进行非阻塞、零字节发送调用?
MSDN 文档底部的示例套接字连接 http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx属性(至少 .NET 3.5 版本)显示了如何执行此操作:
// .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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)