gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:11:23 25 4
gpt4 key购买 nike

有关 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 的 MSDN 文档底部的示例属性(至少是 .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);

关于c# - 如何在 C# 中进行非阻塞套接字调用以确定连接状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1363682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com