O'Reilly logo

Network Programming with Rust by Abhishek Chanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required