C++中的并发 TCP 服务器

Concurrent TCP server in C++

本文关键字:TCP 服务器 并发 C++      更新时间:2023-10-16

我正在尝试使用线程创建一个并发的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++图书馆。