Question

Basically I have a client where I send a string of 10 bytes hellohello to a server and within the server I expect the reply to be 0123456789 back to the client but instead I get hellohello again? I changed the char data_ to char data_out on line 58 in the tcp_server.cpp because I thought that was the place to send packet data out? I'm pretty sure that gets called but for some reason things aren't working like I thought.

This is the server output,

handle read: bytes_transferred10
10
handle write:
0123456789
handle read: bytes_transferred0

I also wonder why did handle read: bytes_transferred0 get called again?

This is the client output,

Enter message: hellohello
Reply is: hellohello

Process returned 0 (0x0)   execution time : 6.484 s
Press any key to continue.

This is the tcp_server.cpp

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

class session
{
public:
  session(boost::asio::io_service& io_service)
    : socket_(io_service)
  {
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
          socket_.async_read_some(boost::asio::buffer(data_, max_length),
          boost::bind(&session::handle_read, this,
          boost::asio::placeholders::error,
          boost::asio::placeholders::bytes_transferred));
  }
void read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred);


private:
  void handle_read(const boost::system::error_code& error,
      size_t bytes_transferred)
  {
      std::cout<<"handle read: bytes_transferred"<<bytes_transferred<<std::endl;
    if (!error)
    {
          read_handler(error, bytes_transferred);
          boost::asio::async_write(socket_,
          boost::asio::buffer(data_, bytes_transferred),
          boost::bind(&session::handle_write, this,
          boost::asio::placeholders::error));
    }
    else
    {
      delete this;
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
      std::cout<<"handle write: "<<std::endl;
      data_out = {'0','1','2','3','4','5','6','7','8','9'};
    if (!error)
    {
            std::cout<<data_out<<std::endl;

            socket_.async_read_some(boost::asio::buffer(data_out, max_length),
            boost::bind(&session::handle_read, this,
            boost::asio::placeholders::error,
            boost::asio::placeholders::bytes_transferred));
    }
    else
    {
      delete this;
    }
  }

  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
  char data_out[max_length];
};
void session::read_handler(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
      std::cout<<bytes_transferred<<std::endl;
}

class server
{
public:
  server(boost::asio::io_service& io_service, short port)
    : io_service_(io_service),
      acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
  {
    start_accept();
  }


private:
  void start_accept()
  {
    session* new_session = new session(io_service_);
    acceptor_.async_accept(new_session->socket(),
        boost::bind(&server::handle_accept, this, new_session,
          boost::asio::placeholders::error));
  }

  void handle_accept(session* new_session,
      const boost::system::error_code& error)
  {
    if (!error)
    {
      new_session->start();
    }
    else
    {
      delete new_session;
    }

    start_accept();
  }

  boost::asio::io_service& io_service_;
  tcp::acceptor acceptor_;
};

int main()
{
  try
  {
    boost::asio::io_service io_service;
    server s(io_service, 4000);

    io_service.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

tcp_client.cpp

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
  try
  {


    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(tcp::v4(), "127.0.0.1", "4000");
    tcp::resolver::iterator iterator = resolver.resolve(query);

    tcp::socket s(io_service);
    s.connect(*iterator);

    using namespace std; // For strlen.
    std::cout << "Enter message: ";
    char request[max_length];
    std::cin.getline(request, max_length);
    size_t request_length = strlen(request);
    boost::asio::write(s, boost::asio::buffer(request, request_length));

    char reply[max_length];
    size_t reply_length = boost::asio::read(s,boost::asio::buffer(reply, request_length));
    std::cout << "Reply is: ";
    std::cout.write(reply, reply_length);
    std::cout << "\n";
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}
Was it helpful?

Solution

Your comment

I think handle_read() calls handle_write() recursively?

is close but not quite correct as there is no recursion here. The documentation explains this nicely:

Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using boost::asio::io_service::post().

Added emphasis is mine. Instead of recursion, It is better to think of these concepts as chaining since one operation such as async_write() is initiated in the handler of another, such as async_read(). The exact specifics depend on the protocol in use.

If you want the server to send the string 0123456789 to the client, fill your buffer before invoking async_write().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top