如何制作具有同步 dataread/write 功能的多客户端服务器?

How to make a multi-client server with synchronous dataread/write functions?

好吧,所以我可能给自己找了个大麻烦。一直以来,我的代码都基于我可能 想要的东西,也就是说,我在一个服务器上使用同步 boost::asio 函数,该服务器可以有多个客户同时。这是:

void session(tcp::socket socket, std::vector<Player>* pl)
{
debug("New connection! Reading username...\n");

/* ...Username verification code removed... */

debug("Client logged in safely as ");
debug(u->name);
debug("\n");

for (;;)
{
    boost::array<unsigned char, 128> buf;

    size_t len = socket.read_some(boost::asio::buffer(buf), error);

    if (error == boost::asio::error::eof)
    {
        debug("Connection ended.\n");
        break; // Connection closed cleanly by peer.
    }
    else if (error)
        throw boost::system::system_error(error); // Some other error.

    DataHeader ins = static_cast<DataHeader>(buf.data()[0]);

    std::vector<unsigned char> response;

    /* ... Get appropiate response... */

    // send response
    boost::system::error_code ignored_error;
    boost::asio::write(socket, boost::asio::buffer(response), ignored_error);
    //debug("Sent ");
    //debug(response.size());
    //debug("B to client.\n");
}
}

正如您从代码中看到的,我在非理想场景中使用了 read_somewrite 函数。现在,问题是,我如何让这段代码同时可用于多个客户端?好吧,我使用了线程:

int main()
{
try
{
    boost::asio::io_context io_context;

    tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 13));

    debug("Ready.\n");
    for (;;)
    {
        std::thread(session, acceptor.accept(), &players).detach(); // Accept incoming clients
    }
}
catch (std::exception& e)
{
    std::cerr << e.what() << std::endl;
}

return 0;
}

现在,直到最近我开始在一台服务器上同时测试多个客户端时,我才对这个设置有任何问题。这使服务器多次崩溃,直到现在,我还以为问题只是连接问题。但是,现在我开始怀疑,"Might the problem be the synchronous functions?"

到目前为止,我看到的所有多客户端服务器示例都使用了异步函数,也许是因为需要它们。所以,我的最后一个问题是,我 真的 需要异步函数吗?这段代码有什么问题导致它崩溃吗?最后,如果需要异步函数,我该如何实现它们?非常感谢!

正如用户 VTT 所指出的,虽然这种方法 可能 工作一点点,但由于资源耗尽而切换到异步函数会更好,所以,我将重做整个服务器来实现它们。