Skip to content

Instantly share code, notes, and snippets.

@lingmujianshi
Created October 14, 2019 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lingmujianshi/51f39b8e2bc28d8db07536cec7dd8d5e to your computer and use it in GitHub Desktop.
Save lingmujianshi/51f39b8e2bc28d8db07536cec7dd8d5e to your computer and use it in GitHub Desktop.
#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