Reputation: 51
I'm struggling to receive data with a synchronous client code that is using datagram Unix sockets with Boost.Asio.
The server seems to be working fine because if I connect to it with netcat I receive data. However, when trying with the code below, it gets stuck in receive_from(). strace shows that the receive_from() system call is called but nothing is received, while strace on the server shows that is trying to send data to the client but it is failing to do so.
boost::asio::io_service io_service;
boost::asio::local::datagram_protocol::socket socket(io_service);
socket.open();
cmd::cmd cmd;
cmd.type = cmd::cmdtype::request;
cmd.id = cmd::cmdid::dumptop;
boost::asio::local::datagram_protocol::endpoint receiver_endpoint("socket.unix");
/* The server receives this data successfully */
socket.send_to(
boost::asio::buffer(reinterpret_cast<char*>(&cmd),
sizeof(cmd)),
receiver_endpoint
);
boost::array<char, 128> recv_buf;
boost::asio::local::datagram_protocol::endpoint ep;
/* When the server sends data, nothing is received here.
Maybe it's an issue with the endpoint??? */
size_t len = socket.receive_from(
boost::asio::buffer(recv_buf), ep);
Upvotes: 3
Views: 4130
Reputation: 7100
The problem is that you've only set up the transmit side.
To also receive over the same socket, you will need to bind to a filename, just as you have on the server side. Here's a modified version of the last few lines of your code:
boost::array<char, 128> recv_buf;
boost::asio::local::datagram_protocol::endpoint ep("socket.unix.client");
// bind to the previously created and opened socket:
socket.bind(ep);
/* now get data from the server */
size_t len = socket.receive_from(
boost::asio::buffer(recv_buf), ep);
The usual idiom is that the server has a well-known file name (socket.unix
in your code) and that each communicating client creates its own unique name by doing something like appending its own pid. This example just uses socket.unix.client
for simplicity but of course that will limit you to exactly one client until you change it.
Upvotes: 1