#include "connection.h"

hwo_connection::hwo_connection(const std::string& host, const std::string& port)
  : socket(io_service)
{
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

hwo_connection::~hwo_connection()
{
  socket.close();
}

jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
  boost::asio::read_until(socket, response_buf, "\n", error);
  if (error)
  {
    return jsoncons::json();
  }
  std::istream s(&response_buf);
  return jsoncons::json::parse(s);
}

void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

#include "connection.h"

hwo_connection::hwo_connection(const std::string& host, const std::string& port)
  : socket(io_service)
{
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(host, port);
  boost::asio::connect(socket, resolver.resolve(query));
  response_buf.prepare(8192);
}

hwo_connection::~hwo_connection()
{
  socket.close();
}

jsoncons::json hwo_connection::receive_response(boost::system::error_code& error)
{
  auto len = boost::asio::read_until(socket, response_buf, "\n", error);
  if (error)
  {
    return jsoncons::json();
  }
  auto buf = response_buf.data();
  std::string reply(boost::asio::buffers_begin(buf), boost::asio::buffers_begin(buf) + len);
  response_buf.consume(len);
  return jsoncons::json::parse_string(reply);
}

void hwo_connection::send_requests(const std::vector<jsoncons::json>& msgs)
{
  jsoncons::output_format format;
  format.escape_all_non_ascii(true);
  boost::asio::streambuf request_buf;
  std::ostream s(&request_buf);
  for (const auto& m : msgs) {
    m.to_stream(s, format);
    s << std::endl;
  }
  socket.send(request_buf.data());
}

Fix case where received message was potentially dropped in C++ bot
Fix case where received message was potentially dropped in C++ bot

The read_until() may leave trailing data to read buffer, and this
was not handled properly by the sample bot.

Big thanks to Mika Urtela for spotting this.

Signed-off-by: Harri Salokorpi <eefb23b8deb8c30dca252cd0ae751b67337dc69f@reaktor.fi>
Signed-off-by: Sami Rosendahl <b33c757bb777642ab0d59c699f8d5782929a814f@reaktor.fi>
