简体   繁体   English

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

[英]How do I make a non-blocking socket call in C# to determine connection status?

the MSDN docs for the Connected property on Socket say the following: Socket上Connected属性的MSDN文档说明如下:

The value of the Connected property reflects the state of the connection as of the most recent operation. Connected属性的值反映了最近操作时的连接状态。 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; 如果调用成功返回或抛出WAEWOULDBLOCK错误代码(10035),则套接字仍然连接; otherwise, the socket is no longer connected. 否则,套接字不再连接。

I need to determine the current state of the connection - how do i make a non-blocking, zero-byte send call? 我需要确定连接的当前状态 - 如何进行非阻塞,零字节发送调用?

The example at the bottom of MSDN documentation for the Socket.Connected property (at least the .NET 3.5 version) shows how to do this: 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);

Just providing additional info based on experience: The comments at the bottom of versions 3.5 and 4 of that documentation page for Socket.Connect describe my experience - the example simply didn't work. 只是根据经验提供额外的信息: Socket.Connect文档页面版本3.5和4底部的注释描述了我的经验 - 这个例子根本不起作用。 Really wish I knew why it works for some and not others. 真的希望我知道它为什么适用于某些人而不是其他人。

As a work-around, despite what the documentation says, I changed the sample to actually send the 1 byte with no flags. 作为一种解决方法,尽管文档说的是,我改变了样本实际发送没有标志的1字节。 This successfully updated the state of Connected property, and is equivalent to sending a keep-alive packet at an interval. 这成功更新了Connected属性的状态,相当于每隔一段时间发送一个keep-alive数据包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM