3

I am writing my own Aerospike client in C ++ and I have a problem: although my request seems to reach the server (if you send nonsense, the connection will be dropped), the server does not return any response.

Here is my code:

#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <iostream>

void read_message(boost::asio::ip::tcp::socket& socket)
{
    for (;;)
    {
      boost::array<char, 1> buf;
      boost::system::error_code error;
      size_t len = socket.read_some(boost::asio::buffer(buf), error);
      if (error == boost::asio::error::eof)
        break;
      else if (error)
        throw boost::system::system_error(error);
      std::cout.write(buf.data(), len);
      std::cout << std::endl;
    }
}

void send_message(boost::asio::ip::tcp::socket& socket, std::string message)
{
    boost::array<char, 1024> buf;
    std::copy(message.begin(), message.end(), buf.begin());
    boost::system::error_code error;
    socket.write_some(boost::asio::buffer(buf, message.size()), error);
}

int main()
{
    std::cout << "Connecting to socket.." << std::endl;
    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 3000);
    boost::asio::ip::tcp::socket socket(ios);
    socket.connect(endpoint);
    std::cout << "Connected to socket. Writing message." << std::endl;
    send_message(socket, "\x02\x01\x00\x00\x00\x00\x006build\nedition\nnode\nservice\nservices\nstatistics\nversion");
    std::cout << "Writed message. Reading response." << std::endl;
    read_message(socket);
    std::cout << "Read response. Exiting prigram." << std::endl;
    socket.close();
    return 0;
}

This code works correctly with, for example, 1.1.1.1:80 - HTML is returned with the words "Bad request".

1 Answers1

2

You are calling socket.write_some() only once in your send_message() function. You are basically assuming that all the bytes will be sent in one call. There is no such guarantee. When I tried your code, it sent only 2 bytes in my run. Unless all bytes reach the server, it won't respond (obviously).

sunil
  • 3,507
  • 18
  • 25