Boost read_also() function not working with boost:

2019-08-21 12:20发布

问题:

I have this code to open a boost socket, write a command, send the command via the socket, and get the results:

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <array>
#include <string>
#define MAXSIZE 1000000
//...
void MyClass::processCommand(std::string command)
{
  boost::asio::io_service io;
  boost::asio::ip::tcp::socket socket(io);
  boost::asio::ip::tcp::endpoint e(boost::asio::ip::address::from_string("127.0.0.1"), 60151);  //Info for the connection I need to make...
  this->socket.open(boost::asio::ip::tcp::v4());
  this->socket.connect(e);
  this->socket.write_some(boost::asio::buffer(command, command.size());
  this->socket.send(boost::asio::buffer(command, command.size());

  boost::array<char, MAXSIZE> buffer;
  this->socket.read_some(boost::asio::buffer(buffer));
}

This code compiles and runs, but freezes on the line calling read_some(), and I can't figure out why. If anyone has any ideas for solutions, I'd greatly appreciate it.

回答1:

You wrote command.size() bytes.

You then asked to read MAXSIZE bytes.

If command.size() < MAXSIZE, why wouldn't it wait for more bytes to come down the pipe?

Try first writing the size of the packet, then the bytes of the packet.

On the reading side, first read the size of the packet, then read that many bytes of the packet.

read_some is free to read less than you requested, but I don't see any documentation that says it must return before it reads as many bytes as you requested.



标签: c++ arrays boost