在我开始之前
Please don't mark this question as a duplicate. 我已经看过很多关于使用套接字编程处理多个客户端的帖子 . Most people recommend just multi-threading ,但我试图避开那条路,因为我读过它有一些问题:
-
糟糕的可扩展性
-
大开销/低效/内存饥饿
-
难以调试
我读过的任何专门讨论使用单个帖子的帖子都有错误/无答案或者解释不清楚,就像有人说“只要使用 select()
!”
问题
我正在为服务器编写代码来处理多个(~1000)客户端,而我无法确定如何创建有效的解决方案 . 现在我已经有了我的服务器的代码,一次能够处理1个客户端 . 两者都用C语言写成;服务器在Windows上使用WinSock,客户端在Linux上 . 服务器和客户端使用 send()
和阻止 recv()
调用来回发送多个通信 . 编写这段代码非常简单,我不会在这里发布,因为它很长,而且我怀疑任何人都会真正阅读所有内容 . 另外,确切的实现并不重要,我只想谈谈高级伪代码 . 真正的困难是更改服务器以处理多个客户端 .
已经有什么了
我找到了一个很好的PDF教程,关于如何创建一个处理多个客户端的WinSock服务器,可以在这里找到:WinSock Multiple Client Support . 它's in C++ but it'很容易转移到C.
根据我的理解,服务器运行如下:
while (running) {
Sleep(1000);
/* Accept all incoming clients and add to clientArray. */
for (client in clientArray) {
/* Interact with client */
if (recv(...) == "disconnect") {
/* Disconnect from client */
}
}
}
/* Close all connections. */
我看到使用这种方法的问题是 you essentially only handle one client at a time (which is obvious because you aren't multithreading) ,但是如果与每个客户端的交互只需要发生一次呢?意思是,如果我只想来回发送一些数据并关闭连接怎么办? This operation could take anywhere from 5 seconds to 5 minutes depending on the speed of the clients connection, so other clients would be blocking on a connect() call to the server while the server handles a client for 5 minutes. 它不确定,但它让我很好奇大型服务器如何同时向数千个客户端发送更新下载,如果我应该以相同的方式运行 .
另外,如果服务器和客户端之间的 send()
和 recv()
需要一段时间(~1分钟),是否有理由在主服务器循环中添加 Sleep(1000)
调用?
我要求的是什么
我想要的是在单线程服务器上处理多个客户端的解决方案,该服务器对于~1000个客户端来说足够有效 . 如果你告诉我PDF中的解决方案没问题,这对我来说已经足够了(也许我只是太专注于效率了 . )
Please give answers that include a verbal explanation of the implementation, server/client pseudocode, or even a small sample code for the server ,如果你感到虐待狂 . )
提前致谢 .