Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#ifndef UDPCLIENT_HPP
#define UDPCLIENT_HPP
#define ASIO_STANDALONE
#include <asio.hpp>
class UDPClient
{
private:
asio::ip::udp::endpoint endpoint;
asio::ip::udp::socket socket;
public:
UDPClient(
asio::io_context& io_contex,
const std::string host,
const short port)
: socket(io_contex)
{
asio::ip::udp::endpoint endpoint_(asio::ip::address::from_string(host), port);
endpoint = endpoint_;
}
~UDPClient()
{
Close();
}
void Open()
{
socket.open(asio::ip::udp::v4());
}
void Close()
{
socket.close();
}
template <typename T>
void Send(T msg,int size)
{
socket.send_to(asio::buffer(&msg, size), endpoint);
}
};
#endif
#define ASIO_STANDALONE
#include <asio.hpp>
#include <iostream>
#include "UDPClient.hpp"
int main(int argc, char const *argv[])
{
asio::io_context io_context;
const std::string host = "127.0.0.1";
const short port = (short)60000;
UDPClient udp(io_context,host,port);
udp.Open();
for(;;)
{
std::string inmsg;
getline(std::cin, inmsg);
if(inmsg=="q") break;
inmsg+="\r\n\r\n";
udp.Send(inmsg,inmsg.size());
}
udp.Close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment