处理多个客户端的单个 TCP/IP 服务器(在 C++ 中)?

2021-12-20 00:00:00 sockets multithreading networking tcp c++

我想用 C++ 编写一个 TCP/IP 服务器(使用 bind()accept() 等),它可以处理连接到它的多个客户端同一时间.我已经阅读了一些关于此的主题,每个人都提出了以下建议(即将出现脏伪代码):

I want to write a TCP/IP server in C++ (using bind(), accept() etc.) that can deal with multiple clients connecting to it at the same time. I have read a few topics about this, and everyone is suggesting the following (dirty pseudocode coming up):

set up server, bind it

while (1) {
    accept connection
    launch new thread to handle it
}

在具有多个线程的机器上完全可以正常工作.但是我的目标系统是没有任何硬件线程的单核机器.作为一个小测试,我尝试通过系统上的 std::thread 启动多个线程,但它们一个接一个地执行.没有平行的好处:(

Which would work totally fine on a machine that has multiple threads. But my target system is a single core machine without any hardware threads. For a little test, I tried launching multiple threads via std::thread on the system but they were executed one after the other. No parallel goodness :(

这使得上面的算法无法实现.我的意思是,我确定它可以完成,但我不知道如何完成,所以我非常感谢您的帮助.

That makes it impossible to implement the algorithm above. I mean, I'm sure it can be done, I just don't know how, so I would really appreciate any help.

推荐答案

您不需要线程,您需要异步或事件驱动"编程.如果您想要跨平台,可以使用 select() 或 epoll() 如果您使用 Linux 并希望一次支持数千个客户端,则可以完成此操作.

You don't need threads, you need asynchronous or "event-driven" programming. This can be done with select() if you want cross-platform, or epoll() if you're on Linux and want to support thousands of clients at once.

但是你不需要从头开始实现这一切――你可以使用 Boost ASIO(其中一些可能成为 C++17 的一部分)或像 libevent 或 libev 或 libuv.这些将为您处理大量细微的细节,并帮助您更快地了解应用程序的实际业务.

But you don't need to implement this all from scratch--you can use Boost ASIO (some of which may become part of C++17) or a C library like libevent or libev or libuv. Those will handle a bunch of subtle details for you, and help you get more quickly to the real business of your application.

相关文章