Skip to content

Instantly share code, notes, and snippets.

@MatteoRagni
Last active September 10, 2019 14:44
Show Gist options
  • Save MatteoRagni/85a57d80990bac78bb7b3cd47e60cb34 to your computer and use it in GitHub Desktop.
Save MatteoRagni/85a57d80990bac78bb7b3cd47e60cb34 to your computer and use it in GitHub Desktop.
UDP Sender via BOOST ASIO
#ifndef UDP_HH_
#define UDP_HH_
#include <array>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>
class UDPSender {
std::string ip;
uint16_t port;
boost::asio::io_service io_srvc;
boost::asio::ip::udp::socket socket;
boost::asio::ip::udp::endpoint remote_endpoint;
public:
UDPSender()
: ip(std::string{"127.0.0.1"}),
port(5006),
socket(boost::asio::ip::udp::socket{io_srvc}),
remote_endpoint(boost::asio::ip::udp::endpoint{boost::asio::ip::address::from_string(ip), port}) {}
UDPSender(const std::string& ip_, const uint16_t port_)
: ip(ip_),
port(port_),
socket(boost::asio::ip::udp::socket{io_srvc}),
remote_endpoint(boost::asio::ip::udp::endpoint{boost::asio::ip::address::from_string(ip), port}) {}
void open() { socket.open(boost::asio::ip::udp::v4()); }
void close() { socket.close(); }
size_t send(const char * buffer, size_t len) {
return socket.send_to(boost::asio::buffer(buffer, len), remote_endpoint);
}
};
#endif /* UDP_HH_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment