-
-
Save DanielKotik/63757c778e7baf30f4a7737a01469062 to your computer and use it in GitHub Desktop.
Super simple UDP client using boost
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
/* | |
This Program uses OS independet boost library 'asio'. | |
Below are some web links for programming UDP sockets with linux specific libraries using functions: 'gethostbyname', 'bind' and | |
'socket'. Please note, however, that these functions are superseded by 'getaddrinfo' and 'getnameinfo' nowadays. These functions | |
provide better support for IPv6. | |
https://www.ibm.com/developerworks/library/wa-ipv6.html | |
http://openbook.rheinwerk-verlag.de/linux_unix_programmierung/Kap11-016.htm#RxxKap11016040003951F04F100 | |
https://www.cs.rutgers.edu/~pxk/417/notes/sockets/udp.html | |
*/ | |
#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