Created
April 16, 2014 23:16
-
-
Save hsalokor/10941596 to your computer and use it in GitHub Desktop.
Better buffer handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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) | |
{ | |
size_t len = boost::asio::read_until(socket, response_buf, "\n", error); | |
if (error) | |
{ | |
return jsoncons::json(); | |
} | |
std::string reply; | |
buffer_type input = response_buf.data(); | |
std::copy(iterator::begin(input), iterator::end(input), std::back_inserter(reply)); | |
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()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef HWO_CONNECTION_H | |
#define HWO_CONNECTION_H | |
#include <string> | |
#include <iostream> | |
#include <boost/asio.hpp> | |
#include <jsoncons/json.hpp> | |
using boost::asio::ip::tcp; | |
class hwo_connection | |
{ | |
public: | |
typedef boost::asio::streambuf::const_buffers_type buffer_type; | |
typedef boost::asio::buffers_iterator<buffer_type> iterator; | |
hwo_connection(const std::string& host, const std::string& port); | |
~hwo_connection(); | |
jsoncons::json receive_response(boost::system::error_code& error); | |
void send_requests(const std::vector<jsoncons::json>& msgs); | |
private: | |
boost::asio::io_service io_service; | |
tcp::socket socket; | |
boost::asio::streambuf response_buf; | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment