LIBWIRE
Next-generation C++17 networking library.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
udp_echo_server.cpp
Go to the documentation of this file.
1 #include <iostream>
2 #include <libwire/udp.hpp>
3 #include <libwire/endpoint.hpp>
4 
23  constexpr size_t max_msg_size = 64;
24 
25 int main(int argc, char** argv) {
26  using namespace libwire;
27  using namespace std::literals::string_view_literals;
28 
29  if (argc != 2) {
30  std::cerr << "Usage: echo-server <port>\n";
31  return 1;
32  }
33 
34  uint16_t port = std::stoi(argv[1]);
35  std::cout << "Listening on port " << port << ".\n";
36 
37  udp::socket sock(ip::v4);
38  sock.listen({ipv4::loopback, port});
39 
40  endpoint source{{0, 0, 0, 0}, 0};
41  std::string buf;
42  while (true) {
43  try {
44  sock.read(max_msg_size, buf, &source);
45 
46  size_t lf = buf.find_last_of('\n');
47  if (lf != buf.npos) {
48  buf.resize(lf); // cut LF if present.
49  }
50 
51  std::cout << "< " << buf << '\n';
52  std::cout << "> " << buf << '\n';
53 
54  buf.push_back('\n');
55  sock.write(buf, source);
56  } catch (std::system_error& ex) {
57  std::cout << "ERR: " << ex.what() << '\n';
58  }
59  }
60 }
size_t write(const Buffer &, std::error_code &, const endpoint &dest=endpoint::invalid) noexcept
Write contents of buffer to socket.
Definition: socket.hpp:287
address loopback
Definition: address.hpp:132
void listen(endpoint target, std::error_code &ec) noexcept
Accept datagrams coming on specified endpoint.
int main(int argc, char **argv)
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
constexpr size_t max_msg_size