boost.asio async_receive 永不解决

boost.asio async_receive never resolve

我正在尝试通过实现回显服务器来了解 asio 的工作原理。但它从不回应任何东西!

这是我的代码(请忽略资源泄漏):

#include<boost/asio.hpp>
#include<cstdio>

boost::asio::io_service ioService;

void echo(boost::asio::ip::tcp::socket* socket) {
    char* buf = new char[1024];
    socket->async_receive(boost::asio::buffer(buf, 1023), [buf, socket](auto ec, auto s) {
        if (ec) {
            std::printf("read failed: %s!\n", ec.message().data());
        }
        else
        {
            buf[s] = '[=12=]';
            std::printf("read:%s!\n", buf);
            socket->async_send(boost::asio::buffer(buf, s), [socket](auto ec, auto s) {
                if (ec) {
                    std::printf("write failed: %s!\n", ec.message().data());
                }
                else {
                    echo(socket);
                }
            });
        }
    });
}

void accept(boost::asio::ip::tcp::acceptor& acceptor) {
    auto socket = new boost::asio::ip::tcp::socket{ ioService };
    acceptor.async_accept(*socket, [socket](auto ec) {
        if (ec) {
            std::printf("accept failed:%s!\n", ec.message().data());
        }
        else {
            std::printf("accept %s!", socket->remote_endpoint().address().to_string().data());
            echo(socket);
        }
    });
}

int main() {
    try {
        boost::asio::ip::tcp::acceptor acceptor{ ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8000) };
        accept(acceptor);
        while (true)
        {
            ioService.poll();
        }
    }
    catch (std::exception&e) {
        std::printf("error: %s\n", e.what());
    }
}

我正在使用 Java TCP 客户端(我已经使用 Java TCP 回显服务器对其进行了测试)连接并向该服务器发送消息。唯一有效的是接受函数。我可能哪里出错了?

问题是:

    while (true)
    {
        ioService.poll();
    }

你想要的是删除 while 循环并使用 "run" 方法:

     ioService.run();

实际的问题是你必须调用“restart" method (or the older reset 旧版本的 asio 方法,在你的代码中看起来就是这种情况),然后才能再次调用 poll。循环的另一个问题是当无事可做时,CPU 它的 运行 将处于 100%,因为它处于硬循环中什么都不做......如果你使用 "run" 方法, CPU 无事可做时将使用 0%。

例如

while (true)
{
    ioService.poll();
    ioService.reset();
}

引用ASIO文档:

This function must be called prior to any second or later set of invocations of the run(), run_one(), poll() or poll_one() functions when a previous invocation of these functions returned due to the io_context being stopped or running out of work. After a call to restart(), the io_context object's stopped() function will return false.