docs

You are reading the docs for v0.1.0. Nabi 0.1.0 is no longer supported. Latest release: v0.1.3 →

#TCP echo server

On this page

One program starts an echo server on a free 127.0.0.1 port, has clients send lines and read back the echoes, and then shuts everything down cleanly.

#Code

#Walkthrough

  • Binding TcpListener to port 0 lets the OS choose a free port, and local_addr() reports the actual address, so there is no clash with other programs. bind and connect take text, a SocketAddr or anything else that implements ToSocketAddrs (3.2 net, TcpListener).
  • The server thread starts one handler thread per connection, then joins them all and adds up the lines served. The closures capture listener and conn and carry them to the other threads (Concurrency, thread::spawn).
  • To read line by line while writing, the socket is split() into a read half, wrapped in a BufReader, and a write half: each half owns its direction (split halves, BufReader).
  • Every socket is closed by its owner: the server handler closes both halves (r.into_inner().close(), w.close()), the client closes its write half and leaves its using block, the listener once all clients are served. Leaving one open is a compile error, since its close can fail.
  • Shutdown order matters. After sending everything, the client closes its write half to say "nothing more" (a shutdown(Write), the read half stays open), and the server's lines() ends its loop on that signal. Once the server closes both halves, the socket closes and the client's read_line reads 0 bytes.
  • The same server can be written with accept_async / read_async and tasks instead of the blocking API (3.2.0 common rules).

Found a mistake? Edit this page on GitHub. Last updated