Created
October 14, 2019 03:27
-
-
Save lingmujianshi/51f39b8e2bc28d8db07536cec7dd8d5e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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