A Simple TCP server and client

Most networking examples start with an echo server. So, let's go ahead and write a basic echo server in Rust to see how all the pieces fit together. We will use the threading model from the standard library for handling multiple clients in parallel. The code is as follows:

// chapter3/tcp-echo-server.rsuse std::net::{TcpListener, TcpStream};use std::thread;use std::io::{Read, Write, Error};// Handles a single clientfn handle_client(mut stream: TcpStream) -> Result<(), Error> {    println!("Incoming connection from: {}", stream.peer_addr()?);    let mut buf = [0; 512];    loop {        let bytes_read = stream.read(&mut buf)?;        if bytes_read == 0 { return Ok(()); }        stream.write(&buf[..bytes_read])?;    }}fn main() { let listener ...

Get Network Programming with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.