c++ - C++ 中的并发 TCP 服务器

标签 c++ tcp concurrency server

我正在尝试使用线程创建并发 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/

相关文章:

c++ - CMake 错误 : Cannot determine link language for target

c# - TCP 连接的可靠性如何?

C# - 向 IP 地址和端口发送和接收 TCP/IP 消息

java - 微服务和事务管理器如何处理并发问题

c++ - *&是什么意思

c++ - 如何计算余数有什么不同吗?

c++ - 无法使用std::greater,其中使用了std::less

python - POX - 安装一条规则,当某个数据包与 ofp_match 匹配时发送一个虚拟数据包

C#多线程并发机制等待给定结果

java - block /方法中控制并发的逻辑