简体   繁体   English

不会调用Boost asio async_write回调

[英]Boost asio async_write callback doesn't get called

I'm trying to write a simple server to send messages asynchronously, but my callback for async_write doesn't get called. 我正在尝试编写一个简单的服务器来异步发送消息,但我的async_write回调不会被调用。 By the way, data is succesfully transmitted to the client. 顺便说一句,数据成功传输到客户端。

Firs, my server initialisation code: 第一,我的服务器初始化代码:

void Server::start()
{
    ioService = new boost::asio::io_service();
    acceptor = new tcp::acceptor(*ioService, tcp::endpoint(tcp::v4(), port));

    serverRunning = true;

    serverThread = new boost::thread(&Server::run, this);
    startAccept();
}

My start accept and accept handler methods: 我开始接受并接受处理程序方法:

void Server::startAccept()
{
    serverSocket = new tcp::socket(acceptor->get_io_service());

    acceptor->async_accept(*serverSocket,
        boost::bind(&Server::handleAccept, shared_from_this(),
            boost::asio::placeholders::error));
}

void Server::handleAccept( const boost::system::error_code& error )
{
    changeState(Connected);
}

The handleAccept method get called when i connect, the changeState method does nothing for now. 在连接时调用handleAccept方法,changeState方法暂时不执行任何操作。 After the client connected, i put some data to the toSend vector, and the server's thread sends them: 客户端连接后,我将一些数据放到toSend向量中,服务器的线程发送它们:

void Server::run(){
    while( serverRunning ){
        ioService->poll();

        if (toSend.size()>0 ){
            mtx.lock();
            for (int i=0; i<toSend.size(); i++){
              cout << "async write" << endl;
                boost::asio::async_write(*serverSocket, boost::asio::buffer(toSend.at(i)),
                        boost::bind(&Server::handleSend, shared_from_this(),
                            toSend.at(i),
                            boost::asio::placeholders::error,
                            boost::asio::placeholders::bytes_transferred));
            }
            toSend.clear();
            mtx.unlock();
        }
        usleep(1000);
    }
}

I can see "async write" messages coming on std out, and the client recieves the data as well. 我可以看到std out出现“异步写入”消息,客户端也会收到数据。 My handleSend method is just some cout now, but it never get called. 我的handleSend方法现在只是一些cout,但它永远不会被调用。 Why? 为什么?

If you really want to poll the io_service manually, do this after it gets some work, and call reset between the iterations . 如果您真的想手动poll io_service ,请在完成某些工作执行此操作,并在迭代之间调用reset

Besides, do not call asio::async_write in a loop - the data won't arrive in the correct order. 此外,不要在循环中调用asio::async_write - 数据不会以正确的顺序到达。 Instead, either prepare a single sequence of buffers and send it at once, or chain async_write - completion handler - async_write , as shown in the examples. 相反,要么准备单个缓冲区序列并立即发送它,要么链async_write - completion handler - async_write ,如示例所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM