持续提升:: asio读取 [英] Continuous boost::asio reads

查看:34
本文介绍了持续提升:: asio读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试验Boost :: asio,并且正在尝试创建一个客户端,该客户端可以读取并输出以控制台从服务器发送的数据包.服务器使用专有协议.它每秒发送一次计时器更新,响应ping,并在客户端要求时以文件列表进行回复.我对异步网络有很好的了解,但是我有一个问题.这是代码:

I'm experimenting with Boost::asio, and I'm trying to make a client that reads and outputs to console packets sent from a server. The server uses a proprietary protolcol. It sends a timer update every second, responds to ping, and can reply with a list of files when the client asks for it. I have a decent grasp of asynchronous networking, but I'm having a problem. Here's the code:

class JReader
{
public:
  JReader(boost::asio::io_service &io_s)
    : socket_(io_s)
  {
    tcp::resolver resolver(io_s);
    tcp::resolver::query query("xxxx", "yyyy");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
    tcp::resolver::iterator end;

    boost::system::error_code error = boost::asio::error::host_not_found;
    while (error && endpoint_iterator != end)
    {
      socket_.close();
      socket_.connect(*endpoint_iterator++, error);
    }
    if (error)
    {     
      throw boost::system::system_error(error);
    }


    boost::asio::async_write(socket_, boost::asio::buffer(connect, 12), boost::bind(&JReader::handle_write, this));
    boost::asio::async_write(socket_, boost::asio::buffer(getlist, 3), boost::bind(&JReader::handle_write, this));

    boost::asio::async_read(socket_, boost::asio::buffer(buf_, BUF_SIZE), boost::bind(&JReader::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  }
private:

  void handle_read(const boost::system::error_code err, size_t bytes)
  {        
    std::cout<<std::endl<<std::string(buf_, bytes);
    boost::asio::async_read(socket_, boost::asio::buffer(buf_, BUF_SIZE), boost::bind(&JReader::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
  }

  void handle_write()
  {
    //TODO: finish this!
    std::cout<<std::endl<<"Wrote something";

  }

  static const int BUF_SIZE = 256;
  char buf_[BUF_SIZE];
  tcp::socket socket_;
};

程序从服务器读取并将数据输出到控制台-但是主板发出刺耳的蜂鸣声.我很确定这与我的handle_read循环有关.

The program reads from the server and outputs data to console -- but the motherboard makes a terrible beeping sound. I'm pretty sure it has something to do with my handle_read loop.

连续监听服务器的正确,无阻塞方式是什么?

What is the correct, nonblocking way of continually listening to a server?

推荐答案

啊哈!我对asio的使用是正确的,但是我的错误是将二进制数据流式传输到std :: cout!我改用了文件流,现在它可以工作了.:)

Ah ha! My use of asio was correct, but my mistake was streaming binary data to std::cout!! I used a filestream instead, and now it works. :)

这篇关于持续提升:: asio读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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