Skip to content

Instantly share code, notes, and snippets.

@fortruce
Created August 25, 2015 00:17
Show Gist options
  • Save fortruce/828bcc3499eb291e7e17 to your computer and use it in GitHub Desktop.
Save fortruce/828bcc3499eb291e7e17 to your computer and use it in GitHub Desktop.
Simple TCP Echo Server in Rust
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::io::Read;
use std::io::Write;
fn handle_client(mut stream: TcpStream) {
// read 20 bytes at a time from stream echoing back to stream
loop {
let mut read = [0; 1028];
match stream.read(&mut read) {
Ok(n) => {
if n == 0 {
// connection was closed
break;
}
stream.write(&read[0..n]).unwrap();
}
Err(err) => {
panic!(err);
}
}
}
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move || {
handle_client(stream);
});
}
Err(_) => {
println!("Error");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment