使用boost :: asio :: async_read()时出现问题 [英] Problems using boost::asio::async_read()

查看:635
本文介绍了使用boost :: asio :: async_read()时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用的代码:

class Server
{
.....

void Server::accepted()
{
    std::cout << "Accepted!" << std::endl;

    boost::array<char, 1> buf;
    boost::asio::async_read(socket, boost::asio::buffer(buf),
        boost::bind(&Server::handleRead, this, buf, boost::asio::placeholders::error));
}

void Server::handleRead(boost::array<char, 1> buf, const boost::system::error_code& error)
{
    if(!error)
    {
        std::cout << "Message: " << buf.data() << std::endl;
    }
    else
    {
        std::cout << "Error occurred." << std::endl;
    }
}

.....
}

问题是我总是从客户端获得相同的数据:一个特定的字符. 在我的客户端中,我尝试发送其他字符,但是服务器仍然显示相同的字符.

The problem is that I always get the same data from the client: a specific char. In my client I tried sending other char, but still the server shows the same char.

当我尝试读取1个以上的字节时,我收到一个错误,提示buf变量在初始化之前就已使用.

And when I try to read more than 1 bytes, I get an error that the buf variable is used before it's initialized.

推荐答案

您正在使用局部变量buf作为读取缓冲区,这很危险,无法使用.另外,您只是将缓冲区的原始内容发送到处理程序.因此,您需要使用使用寿命更长的缓冲区.像这样:

You're using the local variable buf as the read buffer, which is dangerous and won't work. Also, you're just sending the original contents of that buffer to the handler. So instead, you need to use a buffer with a longer lifetime. Something like this:

class Server
{
.....

boost::array<char, 1> buf;

void Server::accepted()
{
    std::cout << "Accepted!" << std::endl;

    boost::asio::async_read(socket, boost::asio::buffer(buf),
        boost::bind(&Server::handleRead, this, boost::asio::placeholders::error));
}

void Server::handleRead(const boost::system::error_code& error)
{
    if(!error)
    {
        std::cout << "Message: " << buf.data() << std::endl;
    }
    else
    {
        std::cout << "Error occurred." << std::endl;
    }
}

.....
}

编辑:或者使用堆分配的缓冲区(不确定代码是否正确,但是您会明白的):

edit: or alternatively, using a heap allocated buffer (not sure if the code is right, but you'll get the idea):

void Server::accepted()
{
    std::cout << "Accepted!" << std::endl;

    boost::shared_ptr<boost::array<char, 1>> buf(new boost::array<char, 1>);

    boost::asio::async_read(socket, boost::asio::buffer(*buf),
        boost::bind(&Server::handleRead, this, buf, boost::asio::placeholders::error));
}

void Server::handleRead(boost::shared_ptr<boost::array<char, 1>> buf, const boost::system::error_code& error)
{
    if(!error)
    {
        std::cout << "Message: " << buf->data() << std::endl;
    }
    else
    {
        std::cout << "Error occurred." << std::endl;
    }
}

这篇关于使用boost :: asio :: async_read()时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆