Example TCP server written in Rust [closed]

Here is a very simple example using std::net. It was developed against the current master of Rust and should work on 1.* also.

Be careful with this example; it is simplified; you may not want it to panic if binding, listening or accepting produce an error.

use std::io::Write;
use std::net::TcpListener;
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:9123").unwrap();
    println!("listening started, ready to accept");
    for stream in listener.incoming() {
        thread::spawn(|| {
            let mut stream = stream.unwrap();
            stream.write(b"Hello World\r\n").unwrap();
        });
    }
}

Note the paradigm with regards to accepting; you must initiate the accept() request yourself (in this example we’re using the incoming() iterator which just calls accept() each time), and so you get real control of what tasks there are.

In consequence, I’ve put the actual stream-handling code into a separate thread, but it needn’t be for very short requests (it just means that you would not be able to handle a second request while handling the first); you could just as well remove the thread::spawn(|| { ... }) about those two lines. The use of additional threads gives a certain degree of isolation, also; if the thread unwinds, the server as a whole will not die (bear in mind, however, that running out of memory or having a destructor panic while unwinding will cause the whole server to die).

Leave a Comment