问题描述
在C#.NET中,我试图避免在套接字服务器绑定到&之前套接字客户端尝试连接到端点的竞争条件。监听该端点。
实现此目的的一种方法是,如果客户端在服务器侦听端点之前尝试调用`connect()`方法,客户端无限期等待,直到服务器正在监听。
查看[命名管道文档] [1],我看到`NamedPipeClientStream.ConnectAsync()`方法将"异步连接到具有**无限超时**周期的等待服务器"。是的,这就是我想要的。
但是查看[套接字文档] [2],使用`Socket.ConnectAsync()`方法,没有似乎是一种设置超时期限的方法。编写一个测试程序,我看到如果客户端事实上
在服务器监听端点之前尝试连接,则会抛出`EADDRNOTAVAIL` [(Linux error 99)] [3]。
**有没有办法让`Socket.ConnectAsync()`方法等待套接字服务器监听端点而不是只抛出异常?**
[1]:https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeclientstream.connectasync?view = networkwork4.8
[2]:https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connectasync?view = networkwork-4.8#System_Net_Sockets_Socket_ConnectAsync_System_Net_Sockets_SocketAsyncEventArgs_
[3]:https://mariadb.com/kb/en/library/operating-system-error-codes/
In C# .NET, I'm attempting to avoid a race condition where a socket client tries to connect to an endpoint before a socket server is bound to & listening on that endpoint.
One way to accomplish this is, if the client attempts to call a `connect()` method before the server is listening on the endpoint, the client waits indefinitely until the server is listening.
Looking in [documentation on Named Pipes][1], I see that `NamedPipeClientStream.ConnectAsync()` method will "asynchronously connect to a waiting server with an **infinite timeout** period". Yes, that's what I want.
However looking in [documentation on Sockets][2], using the `Socket.ConnectAsync()` method, there doesn't seem to be a way to set a timeout period. Writing a test program, I see that `EADDRNOTAVAIL` [(Linux error 99)][3] is thrown if the client does in fact attempt to connect before the server is listening to the endpoint.
**Is there any way to make the `Socket.ConnectAsync()` method wait for a socket server to listen to an endpoint instead of just throwing an exception?**
[1]: https://docs.microsoft.com/en-us/dotnet/api/system.io.pipes.namedpipeclientstream.connectasync?view=netframework-4.8
[2]: https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.connectasync?view=netframework-4.8#System_Net_Sockets_Socket_ConnectAsync_System_Net_Sockets_SocketAsyncEventArgs_
[3]: https://mariadb.com/kb/en/library/operating-system-error-codes/
推荐答案
感谢您在此发帖。
对于您的问题,您可以尝试以下建议。
For your question, you could try the suggestion below.
var tsk = client.ConnectAsync(host, port);
tsk.Wait(5000);//set the time
有关详细信息,请参阅以下链接。
For more details, you could refer to the link below.
最好的问候,
Wendy
这篇关于如何在服务器监听端点之前调用该方法,使C#套接字客户端方法`Socket.ConnectAsync()`等待服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!