Skip to content

Instantly share code, notes, and snippets.

@nullmastermind
Forked from kaimallea/UDPClient.hpp
Created March 19, 2022 21:37
Show Gist options
  • Save nullmastermind/9601e1d2d9f4d12fc842253458dbb834 to your computer and use it in GitHub Desktop.
Save nullmastermind/9601e1d2d9f4d12fc842253458dbb834 to your computer and use it in GitHub Desktop.
Super simple UDP client using boost
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
class UDPClient
{
public:
UDPClient(
boost::asio::io_service& io_service,
const std::string& host,
const std::string& port
) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
udp::resolver resolver(io_service_);
udp::resolver::query query(udp::v4(), host, port);
udp::resolver::iterator iter = resolver.resolve(query);
endpoint_ = *iter;
}
~UDPClient()
{
socket_.close();
}
void send(const std::string& msg) {
socket_.send_to(boost::asio::buffer(msg, msg.size()), endpoint_);
}
private:
boost::asio::io_service& io_service_;
udp::socket socket_;
udp::endpoint endpoint_;
};
int main()
{
boost::asio::io_service io_service;
UDPClient client(io_service, "localhost", "1337");
client.send("Hello, World!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment