如何让 boost::asio::async_read 在到达终止字符时返回

发布于 2024-10-24 05:34:45 字数 1025 浏览 8 评论 0 原文

我正在使用 boost asio 库从 tcp 套接字读取内容。我的代码如下所示

std::string completeBuffer="";
std::string TcpConnection::readMessage()
{
    LOG4CPLUS_DEBUG(logger, "Start Listener for Reading Message from Connection");
    boost::system::error_code error;
    boost::asio::async_read(socket, boost::asio::buffer(buffer),
        boost::bind(&TcpConnection::handleRead, this, buffer, boost::asio::placeholders::error));
    return buffer.data();
}

void TcpConnection::handleRead(boost::array<char, TcpConnection::BUFFER_SIZE> buf, const boost::system::error_code& error)
{
    if(!error)
    {
       LOG4CPLUS_INFO(logger, "READ Message " << buf.data());
       completeBuffer.append(buf.data());
       buf.assign(0);
       readMessage();
    }

}

现在我正在从其他一些类调用 readMessage()。每当达到 BUFFER_SIZE 时,就会调用 handleRead 并附加内容。

现在的问题是,BUFFER_SIZE 为 50,整个消息大小为 75,handleRead 仅被调用一次,并且缓冲区等待为handleRead 填充 第二次被调用。 有没有办法设置 EOM 字符或字符串,以便 asio 在到达时返回。

i'm using boost asio library to read the content from the tcp socket. My code looks like this

std::string completeBuffer="";
std::string TcpConnection::readMessage()
{
    LOG4CPLUS_DEBUG(logger, "Start Listener for Reading Message from Connection");
    boost::system::error_code error;
    boost::asio::async_read(socket, boost::asio::buffer(buffer),
        boost::bind(&TcpConnection::handleRead, this, buffer, boost::asio::placeholders::error));
    return buffer.data();
}

void TcpConnection::handleRead(boost::array<char, TcpConnection::BUFFER_SIZE> buf, const boost::system::error_code& error)
{
    if(!error)
    {
       LOG4CPLUS_INFO(logger, "READ Message " << buf.data());
       completeBuffer.append(buf.data());
       buf.assign(0);
       readMessage();
    }

}

Now i'm making the call from some other class to readMessage(). whenever the BUFFER_SIZE is reached the handleRead gets called and the content gets appended.

now the question is say the BUFFER_SIZE is 50, and the whole message size is 75, handleRead is called only once and the buffer waits to be filled for the handleRead to be called for the second time.
Is there a way to set the EOM character or string for asio to return whenever its reached.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心凉 2024-10-31 05:34:45

找到答案 async_read_until

Found the answer async_read_until

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文