尝试同时将数百个客户端连接到单个服务器的错误消息(套接字错误 10061)

error message trying to connect a few hundred clients to a single server all at once (socket error 10061)

我创建了一个服务器-客户端应用程序(嗯,我创建了客户端,我的同事用不同的语言创建了服务器)应用程序。当我尝试将 900 多个客户端(所有单独的 TCP 客户端)连接到服务器时,我得到以下异常:

No connection could be made because the target computer actively refused it.

Socket error: 10061

WSAECONNREFUSED

Connection refused. No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

最终,如果我等待足够长的时间,它们将全部连接到 TCP 套接字之上(因为我们已经使我们自己的 reconnect/keep 活动)。因此,如果失败,它将简单地重试直到成功。

我收到这个错误是因为服务器 'overloaded' 并且无法一次处理所有请求(我在一个单独的线程中分别创建 900 个客户端,所以几乎所有的客户端都在尝试连接同时)。

有什么办法可以解决这个问题吗?我们可以调整 TCP 套接字选项,使其可以同时处理更多客户端吗? 还需要注意的是,我 运行 服务器和客户端在同一台机器上, 运行 它在不同机器上似乎减少了错误消息的数量。这就是为什么我认为这是某种容量问题,因为服务器不能那么快地处理它们。

Do I get this error because the server is 'overloaded' and can't handle all the requests all at once (i'm creating 900 clients each in a separate thread so it's pretty much all trying to connect simultaneously).

是的,这太疯狂了(创建 900 个单独的线程,您应该使用 ConcurrentQueue 创建线程池并限制队列)!

您可以使用 Socket.Listen(backlog); 增加积压数量,其中积压是待处理连接队列的最大长度。 backlog 参数被限制为不同的值,具体取决于操作系统。 您可以指定更高的值,但积压将根据操作系统进行限制。

Is there a way to counter act this? can we tweak a TCP Socket option so it can handle more clients all at once?

在这种情况下不是(这里已经是900个请求);但是,一般来说 - YES,在 Socket.Listen(backlog) 中为其他积压较少的情况提供更多积压。此外,使用连接池(已由 .NET 运行时环境管理)和 ConcurrentQueue 按顺序处理线程。但是,请记住,您不能提供比 OS 限制的数量更多的待办事项。 900 对于简单的机器来说太多了!

It might also be good to note that i'm running the server and client on the same machine, running it on different machines seems to reduce the number of error messages.

会的,因为负载已分配到 2 台不同的机器上。但是,你仍然不应该尝试你在做什么。创建一个 ConcurrentQueue 来管理线程(按顺序)。