Search code examples
c++boostboost-asiographite

using boost asio to write to carbon gives broken pipe


I have Grafana and Graphite running on localhost. Everything is setup as default, so the plaintext protocol is configured for port 2003, as described here

The following works as desired:

export SERVER=localhost
export PORT=2003
echo "no_cluster.fake_xen.sample 25 1488542618" | nc  ${SERVER} ${PORT}

Gives me the datapoint I expect (adjust timestamp as needed).

The following minimal compileable example:

#include <chrono>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/asio.hpp>

namespace basio = boost::asio;

void post_to_carbon (std::string message)
{
    using btcp = boost::asio::ip::tcp;
    constexpr const char* carbon_port="2003";
    basio::io_service ios;
    btcp::resolver resolver(ios);
    btcp::resolver::query query("localhost", carbon_port);
    btcp::endpoint carbon_endpoint = *resolver.resolve(query);
    btcp::socket sock(ios,carbon_endpoint);
    boost::system::error_code ignored_error;
    basio::write(sock, basio::buffer(message), ignored_error);
    std::cout << "posting: " << message << " gave: " << ignored_error.message() << "\n";

}

int main() {
    post_to_carbon("no_cluster.fake_xen.sample 25 1488542800");
}

Fails with the error message:

posting: no_cluster.fake_xen.sample 25 1488542800 gave: Broken pipe

Can someone tell me what I'm doing wrong?


Solution

  • The constructor form socket(io_service, endpoint) binds the local endpoint of the socket to the given endpoint.

    I think what you want to do is:

    btcp::socket sock(ios);
    sock.connect(carbon_endpoint /* , error_code */);