Last active
August 31, 2015 16:34
-
-
Save flaviofernandes004/a01c686f42cb2088031e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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