0

我还没有找到解决这个问题的具体参考。我正在使用 boost asynch 示例 3 的修改版本编写服务器。我正在使用 async_read_until。当收到消息时,程序调用句柄读取并调用一个新线程,但streambuf仍然包含分隔符(我正在从不同的项目发送一个xml)并立即调用另一个线程直到我的threadmax。

class server{
    ....
    void server::run()
    {
        std::vector<boost::shared_ptr<boost::thread>> threads;
        for (std::size_t i = 0; i < thread_pool_size_; ++i)
        {
            boost::shared_ptr<boost::thread> thread(new boost::thread(
                boost::bind(&boost::asio::io_service::run, &io_service_)));
            threads.push_back(thread);
        }

        //wait for all threads in the pool to exit.
        for (std::size_t i = 0; i < threads.size(); ++i)
            threads[i]->join();
    }

    void server::start_accept()
    {
        new_connection_.reset(new connection(io_service_, request_handler_));
        acceptor_.async_accept(new_connection_->socket(),
            boost::bind(&server::handle_accept, this,
            boost::asio::placeholders::error));
    }

    void server::handle_accept(const boost::system::error_code& e)
    {
        if (!e)
        {
            new_connection_->start();
        }

        start_accept()
     }
}

class connection{
    ....
    void connection::start()
    {
        boost::asio::async_read_until(socket_, buffer_,
            "<\\User>",
            boost::bind(&connection::handle_read, shared_from_this(),
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }

    void connection::handle_read(const boost::system::error_code& e,
                                 std::size_t bytes_transferred)
    {
        if(!e)
        {
            std::ostringstream ss;
            std::cout << ss.str();
            buffer_.consume(buffer_.size());
        }
    }
4

0 回答 0