Skip to content

Instantly share code, notes, and snippets.

@sw17ch
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sw17ch/9864071 to your computer and use it in GitHub Desktop.
Save sw17ch/9864071 to your computer and use it in GitHub Desktop.
use std::io::net::ip::SocketAddr;
use std::io::net::tcp::{TcpListener, TcpStream};
use std::io::{IoResult, Acceptor, Listener};
fn main() {
let addr = from_str::<SocketAddr>("127.0.0.1:7123").unwrap();
match TcpListener::bind(addr) {
Err(e) => fail!("Unable to bind to {}: {}", addr, e),
Ok(l) => listen(l),
};
}
fn listen(listener: TcpListener) {
match listener.listen() {
Err(e) => fail!("Unable to listen: {}", e),
Ok(mut a) => {
println!("listening...");
for stream in a.incoming() {
handle_incoming(stream);
}
},
};
}
fn handle_incoming(stream: IoResult<TcpStream>) {
match stream {
Err(e) => println!("Unable to listen: {}", e),
Ok(s) => {
spawn(proc () {
handle_client(s);
});
},
}
}
fn handle_client(mut stream: TcpStream) {
let mut buf = [0, ..1024];
loop {
match stream.read(buf.as_mut_slice()) {
Err(e) => fail!("error reading: {}", e),
Ok(len) => {
match stream.write(buf.slice(0, len)) {
Err(e) => fail!("unable to echo: {}", e),
Ok(_) => println!("echoed {:u} bytes", len)
}
},
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment