LIBWIRE
Next-generation C++17 networking library.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
udp_echo_client.cpp
Go to the documentation of this file.
1 #include <iostream>
2 #include <libwire/udp/socket.hpp>
3 #include <libwire/dns.hpp>
4 
17  constexpr size_t max_msg_size = 64;
18 
19 int main(int argc, char** argv) {
20  using namespace libwire;
21  using namespace std::literals::string_view_literals;
22 
23  if (argc != 2 && argc != 3) {
24  std::cerr << "Usage: echo-client <ip> [port]\n";
25  return 1;
26  }
27 
28  uint16_t port = 7;
29  if (argc == 3) {
30  port = uint16_t(std::stoi(argv[2]));
31  }
32 
33  udp::socket socket(ip::v4);
34  socket.associate({dns::resolve(ip::v4, argv[1]).at(0), port});
35 
36  std::string buffer;
37 
38  while (std::cout << "> ", std::getline(std::cin, buffer)) {
39  buffer.push_back('\n');
40  socket.write(buffer);
41  socket.read(max_msg_size, buffer);
42 
43  size_t lf = buffer.find_last_of('\n');
44  if (lf != buffer.npos) {
45  buffer.resize(lf); // cut LF if present.
46  }
47 
48  std::cout << "< " << buffer << '\n';
49  }
50 }
size_t write(const Buffer &, std::error_code &, const endpoint &dest=endpoint::invalid) noexcept
Write contents of buffer to socket.
Definition: socket.hpp:287
void associate(endpoint target, std::error_code &ec) noexcept
Associate UDP socket with remote endpoint.
int main(int argc, char **argv)
This file defines free functions for interaction with system resolver.
Buffer & read(size_t bytes_count, Buffer &, std::error_code &, endpoint *source=nullptr) noexcept
Read pending datagram into buffer.
Definition: socket.hpp:256
Descriptor wrapper for UDP socket.
Definition: socket.hpp:56
This file defines udp::socket type, base class for outgoing UDP communication.
std::vector< address > resolve(ip protocol, const std::string_view &domain, std::error_code &ec) noexcept
Resolve domain name to one or more IP addresses of 'protocol' version.
constexpr size_t max_msg_size