C++中的并发 TCP 服务器
Concurrent TCP server in C++
我正在尝试使用线程创建一个并发的c ++ TCP服务器。特别是我想知道我是否可以使用 std::async 来接受连接并在自己的线程中为每个连接提供服务。
到目前为止,我已经创建了一个粗略的模型,但无法真正判断我是否走在正确的道路上。
void networking::TCP_Server::acceptConnection() {
std::string stringToSend{"This is a test string to be replied to"};
int new_fd = accept(listeningFD, nullptr, nullptr);
send(new_fd, stringToSend.c_str(), stringToSend.size(), 0);
sleep(3);
std::cout << ("End of thread");
}
///LISTEN FOR CONNECTIONS ON listeningFD
///CREATE A LIST OF FILE DESCRIPTORS FOR POLL fds[]
(fds[i].fd == listeningFD) {
do {
std::cout << ("New incoming connection - %dn", new_fd);
std::async(std::launch::async, acceptConnection)
} while (new_fd != -1);
} /* End of existing connection is readable */
} /* End of loop through pollable descriptors */
我同时使用两个客户端连接到服务器,并希望循环通过两个新连接运行并为每个连接创建一个线程。截至目前,它在延迟模式下运行时,一个被接受,另一个等待第一个完成。
有什么想法吗?
(请原谅代码中的任何错误(
std::async
返回一个代码不会保存到变量中的std::future
,因此会立即调用其析构函数。 std::future::~future()
阻塞调用线程,直到将来准备就绪。
您可能喜欢使用(分离的(std::thread
而不是std::async
。
有更可扩展的策略来处理许多客户端。我强烈建议阅读旧的但有启发性的C10K问题。
您可能还想熟悉Asio C++图书馆。
相关文章:
- 提升 Asio TCP 服务器 处理多个客户端
- 计算出有多少客户端可以连接到我正在使用的一些tcp服务器代码
- TCP 服务器的异步读取使用 boost::asio 打印客户端套接字发送的数据
- 如何将 c++ 中的客户端 TCP 的替身列表发送到 Matlab 中的 TCP 服务器?
- 从 tcp 服务器打开 8MP H264 流时出现问题
- Qt TCP服务器不从客户端读取数据
- C++ TCP 服务器比较字符串失败
- 提升 ASIO TCP 服务器架构
- 使用线程池提升 ASIO 多线程 TCP 服务器
- 如何在C++中终止具有键盘输入的侦听 TCP 服务器
- 简单的非阻塞多线程 tcp 服务器
- TCP 服务器套接字打开失败C++
- TCP 服务器/客户端:客户端 recv() 返回空白缓冲区
- 接收音频块的异步TCP服务器会出现访问违规错误
- 使用Valgrind时,偶尔的BOOST :: ASIO TCP服务器故障在Localhost上运行
- 在使用 Poll() 的 TCP 服务器 - 客户端连接中,我是否需要手动设置事件?我从来没有到达 POLLOUT 来写
- 无法使用C#TCP服务器和C TCP客户端接收消息
- C++ TCP 服务器 (Winsock) 连接 (无效客户端) 然后立即关闭
- 可视化 将 TCP 服务器数据包保存到 C++ 中的文件
- C++中的并发 TCP 服务器