【问题标题】:boost::asio server with simple functions具有简单功能的 boost::asio 服务器
【发布时间】:2017-09-29 13:03:17
【问题描述】:

伙计们,我真的需要你们的帮助。我正在学习 boost::asio 并且我有 2 个问题我无法处理好几天...

下面是一个我自己做的简单回显服务器的例子:

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));
}

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

注意:我在记事本中写了这段代码,如果有语法错误,请见谅。

提前感谢您的帮助!!!

【问题讨论】:

标签: c++ boost-asio


【解决方案1】:

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

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

【讨论】:

  • @Gruffalo,感谢您编辑我的答案,将write_accept 更改为async_accept。但是,@Abor 的代码有一个名为write_accept 的函数,它创建一个newConnection,然后调用async_accept...
猜你喜欢
  • 1970-01-01
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 2012-03-10
  • 2012-03-07
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
相关资源
最近更新 更多