I need to communicate with a different device in a private network over UDP. I am new to using boost, but based on what I searched online and also the tutorials on Boost website
You forget to
io_service
There's no use doing async_*
calls in a loop, because all it does is queue tasks, which won't get executed unless a thread runs io_service::run
.
Live On Coliru
#include
#include
#include
#include
#include
#define IPADDRESS "127.0.0.1" // "192.168.1.64"
#define UDP_PORT 13251
using boost::asio::ip::udp;
using boost::asio::ip::address;
void Sender(std::string in) {
boost::asio::io_service io_service;
udp::socket socket(io_service);
udp::endpoint remote_endpoint = udp::endpoint(address::from_string(IPADDRESS), UDP_PORT);
socket.open(udp::v4());
boost::system::error_code err;
auto sent = socket.send_to(boost::asio::buffer(in), remote_endpoint, 0, err);
socket.close();
std::cout << "Sent Payload --- " << sent << "\n";
}
struct Client {
boost::asio::io_service io_service;
udp::socket socket{io_service};
boost::array recv_buffer;
udp::endpoint remote_endpoint;
int count = 3;
void handle_receive(const boost::system::error_code& error, size_t bytes_transferred) {
if (error) {
std::cout << "Receive failed: " << error.message() << "\n";
return;
}
std::cout << "Received: '" << std::string(recv_buffer.begin(), recv_buffer.begin()+bytes_transferred) << "' (" << error.message() << ")\n";
if (--count > 0) {
std::cout << "Count: " << count << "\n";
wait();
}
}
void wait() {
socket.async_receive_from(boost::asio::buffer(recv_buffer),
remote_endpoint,
boost::bind(&Client::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void Receiver()
{
socket.open(udp::v4());
socket.bind(udp::endpoint(address::from_string(IPADDRESS), UDP_PORT));
wait();
std::cout << "Receiving\n";
io_service.run();
std::cout << "Receiver exit\n";
}
};
int main(int argc, char *argv[])
{
Client client;
std::thread r([&] { client.Receiver(); });
std::string input = argc>1? argv[1] : "hello world";
std::cout << "Input is '" << input.c_str() << "'\nSending it to Sender Function...\n";
for (int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
Sender(input);
}
r.join();
}
Prints
Input is 'hello'
Sending it to Sender Function...
Receiving
Sent Payload --- 5
Received: 'hello' (Success)
Count: 2
Sent Payload --- 5
Received: 'hello' (Success)
Count: 1
Sent Payload --- 5
Received: 'hello' (Success)
Receiver exit