P粉8521147522023-08-21 10:46:01
If this happens all the time, then this actually means that the machine exists, but there is no service listening on the specified port, or there is a firewall blocking you.
If this happens occasionally - you used the word "sometimes" - and the retry succeeds, it's most likely because the server's 'backlog' is full.
While you are waiting to be accepted on a listening socket, you will be placed in a backlog. This backlog is finite and very short - values of 1, 2 or 3 are not uncommon - so the operating system may not be able to queue your request to 'accept' for consumption.
The backlog is a parameter of the listen
function - all languages and platforms basically have the same API in this regard, even C#. If you control the server, this parameter is usually configurable and may be read from some configuration file or registry. Learn how to configure your server.
If you wrote the server, you probably have heavy processing in the accept of the socket, which could be better moved to a separate worker thread, so that your accept is always ready to receive connections. You can explore various architectural options to alleviate queuing and sequential processing on the client side.
Regardless, regardless of whether you can increase the server's backlog, your client code will need retrylogic to deal with this - because even if There is a long backlog, and the server may still receive many requests for other ports at that time.
There is a rare possibility that this error will occur if the NAT router runs out of mapped ports. I think this is too unlikely though, as the router can establish 64K simultaneous connections to the same destination address/port before running out of capacity.