Skip to content

Instantly share code, notes, and snippets.

@noprompt
Last active June 22, 2016 23:38
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 noprompt/2c860e1fd0a36e046baed01d0ee8f289 to your computer and use it in GitHub Desktop.
Save noprompt/2c860e1fd0a36e046baed01d0ee8f289 to your computer and use it in GitHub Desktop.
use std::io::BufRead;
use std::io::BufReader;
use std::io::ErrorKind;
use std::io::Write;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
fn handle_tcp_stream(mut tcp_stream: TcpStream) {
#![allow(unused_must_use)]
let read_timeout = Duration::from_secs(5);
tcp_stream.set_read_timeout(Some(read_timeout.clone()));
let mut buffer = String::new();
let mut reader = BufReader::new(tcp_stream.try_clone().unwrap());
tcp_stream.write(b"Welcome!\n");
loop {
tcp_stream.write(b"Say something in 5 seconds or be disconnected!\n");
match reader.read_line(&mut buffer) {
Ok(amount_read) => {
if amount_read == 0 {
// Client has disconnected.
break;
} else {
// Client has written data.
tcp_stream.write(b"You said: ");
tcp_stream.write(buffer.as_bytes());
buffer.clear();
}
}
Err(error) => {
match error.kind() {
// Reading timed out.
ErrorKind::WouldBlock => {
tcp_stream.write(b"Goodbye!\n");
break;
}
_ => break,
}
}
}
}
}
pub fn run() {
let listener = TcpListener::bind("0.0.0.0:9999").unwrap();
for connection in listener.incoming() {
thread::spawn(move || {
let tcp_stream = connection.unwrap();
handle_tcp_stream(tcp_stream);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment