Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
101 views
in Technique[技术] by (71.8m points)

Example TCP server written in Rust


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...