0

In my code I have both a client and server socket set up to simulate interaction between the two using asio. Unfortunately, something is failing in my read() and I'm not entirely sure what I'm not passing in properly and why. When I run it, it'll wait indefinitely. Might it be something I'm missing?

boost::asio::io_service ioservice;
tcp::acceptor acceptor(ioservice);
tcp::socket client(ioservice);
tcp::socket server(ioservice);

boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 2222);

acceptor.open(endpoint.protocol());
acceptor.bind(endpoint);
acceptor.listen();
acceptor.async_accept(server, &acc_handle);

client.async_connect(endpoint, &conn_handle);

ioservice.run();

boost::asio::write(client, boost::asio::buffer("test"));

boost::asio::streambuf bfr;
boost::asio::read(client, bfr);

EDIT: Added handlers, they just log information so I'm omitting their definition.

  • this isn't real code. async_connect etc require handlers. – Richard Hodges Mar 30 '17 at 23:46
  • You're writing to the client socket, but not reading from the server socket (which is where you're intending 'test' to emerge from). No where have you written anything to the server socket, so there is nothing to read from the client socket. – bazza Mar 31 '17 at 03:23
  • @bazza that's how network services usually work though, the other party is usually not the same program. – sehe Mar 31 '17 at 11:23
  • @bazza The problem if I try to read from the server socket is that I'll get a "Bad File Descriptor" error, which lead me to believe I couldn't use it directly. –  Mar 31 '17 at 14:12

1 Answers1

0

If this is the real flow of code, then nothing after ioservice.run(); gets executed until you stop it at which point no ioservice operations get executed either. The code needs to reside in those async handlers.

It's hard to get a hang on what is going on since you've not included the handlers' definitions but I will try to make a projection:

The acc_handle should contain a server.async_receive(read_buffer, [](const boost::system::error_code&, size_t){...});.

The conn_handle, should contain a client.async_send(write_buffer, endpoint, [](const boost::system::error_code&, size_t){...}); at which point you should be able to see the server's receive handler firing.

All that being said, I strongly recommend you going through the relevant examples at http://www.boost.org/doc/libs/1_64_0/doc/html/boost_asio/examples/cpp11_examples.html as they are clearly and cleanly written.

Tom Trebicky
  • 638
  • 1
  • 5
  • 11