具有简单功能的boost :: asio服务器

时间:2017-09-29 13:03:18

标签: c++ boost-asio

伙计我真的需要你的帮助。我正在学习boost::asio我有两个问题,我几天都不能处理......

以下是我自己完成的简单回显服务器示例:

int main(
{
    // crate a server, binding it and listening connections

    // acceptor server;

    //socket client

    server.async_accept(client, boost::bind(accept_handle, _1, &server, &client));

    io_service.run();

    return 0;
}

void accept_handle(const boost::system::error_code& eCode, boost::asio::ip::tcp::acceptor* server, boost::asio::ip::tcp::socket* client)
{
    char data[43];
    client->async_read_some(boost::asio::buffer(data, 20), boost::bind(read_handle, _1, _2, server, client));
}

void read_handle(const boost::system::error_code& eCode, size_t bytes)
{
    char data_buf[20] = "hello";
    client->async_write_some(boost::buufer(data, 5), boost::bind(write_handle, _1, _2, server, client)); 
}

void write_accept(const boost::system::error_code& eCode, size_t bytes)
{
    boost::asio::ip::tcp::socket newConnection(server->get_ioservice)); // taking he io_service of the server

    server->async_accept(newConnection, boost::bind(accept_handle, _1, server, client));
}

问题是服务器接受一个客户端,它不接受其他待处理的客户端..我在哪里做错了

注意:我在记事本中写了这段代码,很抱歉语法错误,如果有的话。

感谢您的帮助!!!

1 个答案:

答案 0 :(得分:1)

代码只能接受一个连接,因为async_accept函数中调用accept_handle

代码也可能存在对象生命周期的问题:使用共享指针管理clients是明智的:Boost async_* functions and shared_ptr's