Skip to content

Instantly share code, notes, and snippets.

@flaviofernandes004
Last active August 31, 2015 16:34
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 flaviofernandes004/a01c686f42cb2088031e to your computer and use it in GitHub Desktop.
Save flaviofernandes004/a01c686f42cb2088031e to your computer and use it in GitHub Desktop.
// To execute run the command: cargo run
// On other console run for examples: echo "hello" | nc 127.0.0.1 8888
use std::net::{TcpListener, TcpStream};
use std::thread;
// traits
use std::io::Read;
use std::io::Write;
fn handle_client(mut stream: TcpStream) {
let mut buf;
loop {
// clear out the buffer so we don't send garbage
buf = [0; 512];
let _ = match stream.read(&mut buf) {
Err(e) => panic!("Got an error: {}", e),
Ok(m) => {
if m == 0 {
// we've got an EOF
break;
}
m
},
};
match stream.write(&buf) {
Err(_) => break,
Ok(_) => continue,
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8888").unwrap();
for stream in listener.incoming() {
match stream {
Err(e) => { println!("failed: {}", e) }
Ok(stream) => {
thread::spawn(move || {
handle_client(stream)
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment