tcp 服务器的异步读取打印客户端套接字发送的数据 boost::asio

Async read for tcp server print the data sent by the socket of the client with boost::asio

我想打印客户端发送的消息。但是在我的函数 handleRead 中,当从缓冲区获取数据并打印时,没有打印任何内容。我不知道怎么做。

void    Network::start()
{
    boost::asio::async_write(m_socket, boost::asio::buffer(m_message),
                             boost::bind(&Network::handleWrite,shared_from_this(),
                                         boost::asio::placeholders::error));
}

void    Network::handleWrite(const boost::system::error_code &error)
{
    if (!error)
            doRead();
    else
            std::cout << error.message() << std::endl;
}

void    Network::handleRead(const boost::system::error_code &error)
    {
    if (!error) {
            std::cout << m_buffer.data()<< std::endl;
            doRead();
    }
    else
            close();
}

void    Network::doRead()
{
    boost::asio::async_read(m_socket,
                            boost::asio::buffer(m_buffer),
                            boost::bind(&Network::handleRead,
                                        shared_from_this(),
                                        boost::asio::placeholders::error));
}

m_buffer 的类型是什么?如果它是一个容器,你必须提前调整它的大小。如果是 asio::streambuf 你至少需要使用接收到的 bytes_transferred 参数 handleRead.

echo 例子很多,我只给你指出几个:

async_read 在缓冲区大小已满之前不会打印消息!