我的缓冲区都会在所有连接中使用

Will my buffer used by all connections?

本文关键字:连接 缓冲区 我的      更新时间:2023-10-16

我有一个创建io_service的主,并将其传递到TcpServer的实例。

TcpServer具有成员std::array<char, 8192> m_buffer。它有4种方法:构造函数,startaccept, handleaccept 和handleread。构造函数仅初始化一些成员并调用startaccept。

StartAccept创建了TcpConnection的共享指针,该指针扩展了std::enable_shared_from_this<TcpConnection。在此之后,请访问m_acceptor.async_accept并将接受绑定到之前提到的处理方法。

这是我的 handleaccept 方法。它使用boost :: asio :: buffer调用async_read_some,该:: buffer使用tcpserver中声明的成员变量。

void TcpServer::handleAccept(std::shared_ptr<TcpConnection> newConnection, const boost::system::error_code &error)
{
    if (!error) {
        //newConnection->start();
        std::cout << "Accepting new connection" << std::endl;
        newConnection->getSocket().async_read_some(
            boost::asio::buffer(m_buffer),
            boost::bind(&TcpServer::handleRead, this, newConnection, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
        );
    }
    startAccept();
}

我不确定,但是如果有多个连接,它们都会使用相同的缓冲对象,对吗?他们可能会覆盖它,不是吗?

是的,所有连接都将使用TcpServer中定义的相同缓冲区。实际上,您应该将缓冲区存储在连接中,而不是在服务器中。

boost::asio::buffer将使用该超载。因此,读取的数据将存储到您的m_buffer中。您应该将buffer存储在连接中,或使用一些同步(即,某些布尔标志,例如is_in_read,但这是不好的主意(。