我正在尝试使用线程创建并发 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 - %d\n", 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()
阻塞调用线程,直到 future 准备就绪。
您可能喜欢使用(分离的)std::thread
而不是 std::async
。
有更多可扩展的策略来处理许多客户端。我强烈推荐阅读旧的但有启发性的 The C10K problem .
您可能还想熟悉 Asio C++ Library .
关于c++ - C++ 中的并发 TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55857325/