Single TCP/IP server that handles multiple clients (in C++)?(处理多个客户端的单个 TCP/IP 服务器(在 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.
这篇关于处理多个客户端的单个 TCP/IP 服务器(在 C++ 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:处理多个客户端的单个 TCP/IP 服务器(在 C++ 中)?
基础教程推荐
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01