Created
April 10, 2015 19:08
-
-
Save jleedev/31623f32e470c5a2cdf1 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
use std::net::{TcpListener, TcpStream}; | |
use std::thread; | |
use std::io::{stderr,Write,Read}; | |
use std::env::args; | |
macro_rules! unwrap_fmt { | |
($expr:expr) => (match $expr { | |
Ok(val) => val, | |
Err(err) => panic!("{}", err) | |
}) | |
} | |
fn server(listen_addr: &str) { | |
println!("Listening on {} ...", listen_addr); | |
let listener = unwrap_fmt!(TcpListener::bind(listen_addr)); | |
for stream in listener.incoming() { | |
match stream { | |
Ok(stream) => { | |
thread::spawn(|| { | |
handle_client(stream) | |
}); | |
} | |
Err(e) => { | |
let _ = write!(&mut stderr(), "{}", e); | |
} | |
} | |
} | |
} | |
fn main() { | |
let args = args().collect::<Vec<_>>(); | |
if args.len() != 2 { | |
println!("usage: {} listen_addr", args[0]); | |
return; | |
} | |
server(&args[1]); | |
} | |
fn handle_client(mut stream: TcpStream) { | |
println!("Connection from {}", stream.peer_addr().unwrap()); | |
let mut total = 0us; | |
for b in unwrap_fmt!(stream.try_clone()).bytes() { | |
total += 1; | |
unwrap_fmt!(stream.write(&[unwrap_fmt!(b)])); | |
} | |
println!("Echoed {} bytes to {}", | |
total, stream.peer_addr().unwrap()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment