Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example TCP server written in Rust [closed]

Tags:

tcp

rust

I'm looking for an example of a TCP server in Rust.

Either an 'hello world' or an echo server would be great.

like image 832
fadedbee Avatar asked Jul 03 '13 10:07

fadedbee


2 Answers

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

like image 168
Chris Morgan Avatar answered Sep 18 '22 11:09

Chris Morgan


Simple TCP echo-server https://gist.github.com/seriyps/fd6d29442e16c44ba400

#![feature(phase)] #[phase(plugin, link)] extern crate log; extern crate green; extern crate rustuv;  use std::io; use std::os; use std::io::{Listener,Acceptor,TcpStream};  // This is for green threads. If removed, will spawn 1 OS thread per client. #[start] fn start(argc: int, argv: *const *const u8) -> int {     green::start(argc, argv, rustuv::event_loop, main) }   fn main() {     let host = "127.0.0.1";     let port = 8080;      let sock = io::TcpListener::bind(host, port).unwrap();     let mut acceptor = sock.listen();     for stream in acceptor.incoming() {         match stream {             Err(e) => warn!("Accept err {}", e),             Ok(stream) => {                 spawn(proc() {                     debug!("{}", handle_client(stream));                 })             }         }     } }  fn handle_client(mut stream: io::TcpStream) -> io::IoResult<()> {     info!("New client {}", stream.peer_name());     let mut buf = [0u8, ..4096];     loop {         let got = try!(stream.read(buf));         if got == 0 {             // Is it possible? Or IoError will be raised anyway?             break         }         try!(stream.write(buf.slice(0, got)));     }     Ok(()) } 
like image 32
seriyPS Avatar answered Sep 18 '22 11:09

seriyPS