gpt4 book ai didi

C# 非阻塞 Socket.Connect()

转载 作者:行者123 更新时间:2023-12-03 03:08:18 28 4
gpt4 key购买 nike

我选择不使用异步调用,因为它需要回调,我只是好奇是否有办法通过利用类Unix非阻塞套接字方法来解决这个问题:Poll() ,因为 Asyn 是专门为 Windows 环境创建的。我正在研究是否可以在不异步的情况下完成此操作。

需要注意的是:非阻塞!=异步:)

因此,我通过关闭套接字和 Poll() 方法的阻塞标志来采用以下方法:

    try
{
IPEndPoint hostEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
Socket hostSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
hostSock.Blocking = false;
hostSock.Connect(hostEp);

}
catch (Win32Exception se)
{
if (ex.ErrorCode == 10035) // WSAEWOULDBLOCK is expected, means connect is in progress
while (true)
{
Console.WriteLine("Connecting in progress");
bool connected = hostSock.Poll(1000000, SelectMode.SelectWrite);
if (connected)
{
Console.WriteLine("Connected");
break;
}

}
}

但是 SelectMode.SelectWrite 似乎并没有为我重新启动连接尝试。所以有什么问题?我该如何解决这个问题?我应该使用 Select() instead of Poll()?

最佳答案

只需使用异步方法( ConnectAsync() ),它们就是为此而设计的。不要对程序逻辑使用异常。

您可以同步 Connect() TCP 套接字而不阻塞:

Manual:

The Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection.

You can use SocketException.ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.

If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

但这正是您的代码所做的,因此应该可以正常工作。

关于C# 非阻塞 Socket.Connect(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12086961/

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