Skip to content

Instantly share code, notes, and snippets.

@acuros
Created May 19, 2015 10:34
Show Gist options
  • Save acuros/323dd9fab5f66a504c0b to your computer and use it in GitHub Desktop.
Save acuros/323dd9fab5f66a504c0b to your computer and use it in GitHub Desktop.
Echo Server
use std::io::Write;
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::str;
use std::thread;
fn main() {
let listener = TcpListener::bind("127.0.0.1:9338").unwrap();
println!("Echo Server!");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(move|| {
handle_client(stream);
});
}
Err(e) => {}
}
}
}
fn handle_client(mut stream: TcpStream) {
let mut buf:[u8; 1024] = [0; 1024];
stream.read(& mut buf).unwrap();
print!("Got, {}", utf8_to_string(&buf));
stream.write(&buf).unwrap();
}
fn utf8_to_string(bytes: &[u8]) -> String {
let vector: Vec<u8> = Vec::from(bytes);
String::from_utf8(vector).unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment