LIBWIRE
Next-generation C++17 networking library.
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
tcp_echo_server.cpp
Go to the documentation of this file.
1 #include <iostream>
3 
22 int main(int argc, char** argv) {
23  using namespace libwire;
24  using namespace std::literals::string_view_literals;
25 
26  if (argc != 2) {
27  std::cerr << "Usage: echo-server <port>\n";
28  return 1;
29  }
30 
31  uint16_t port = std::stoi(argv[1]);
32 
33  tcp::listener listener;
34  listener.listen({ipv4::any, port});
35 
36  std::cout << "Listening on port " << port << ".\n";
37 
38  std::string buf;
39  while (true) {
40  auto sock = listener.accept();
41  endpoint source = sock.remote_endpoint();
42 
43  std::cout << "Accepted connection from " << source.to_string() << ".\n";
44 
45  while (true) {
46  try {
47  sock.read_until('\n', buf);
48  std::cout << "< " << buf << '\n';
49  sock.write(buf);
50  sock.write("\n"sv);
51  std::cout << "> " << buf << '\n';
52  } catch (std::system_error&) {
53  break;
54  }
55  }
56 
57  std::cout << "Disconnected.\n";
58  }
59 }
Restricted wrapper for TCP listening socket.
Definition: listener.hpp:51
address any
Definition: address.hpp:132
std::string to_string() const noexcept
Convert endpoint type to string representation.
int main(int argc, char **argv)
void listen(endpoint target, std::error_code &ec, unsigned max_backlog=internal_::socket::max_pending_connections) noexcept
Start listening for incoming connections on specified endpoint.