Skip to content

Instantly share code, notes, and snippets.

@wraithan
Last active August 29, 2015 14:06
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 wraithan/859862bf0f69557c9c4a to your computer and use it in GitHub Desktop.
Save wraithan/859862bf0f69557c9c4a to your computer and use it in GitHub Desktop.
Read data in per line, then print it
use std::io::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};
use std::io::BufferedReader;
fn main() {
let listener = TcpListener::bind("127.0.0.1", 8080);
// bind the listener to the specified address
let mut acceptor = listener.listen();
// accept connections and process them, spawning a new tasks for each one
for stream in acceptor.incoming() {
match stream {
Err(e) => {
println!("connection failed: {}", e);
}
Ok(stream) => spawn(proc() {
handle_client(stream)
})
}
}
}
fn handle_client(stream: TcpStream) {
// Wrap up in BufferedReader to handle utf8 in chunks correctly.
let mut reader = BufferedReader::new(stream);
// Infinitely read.
loop {
// Process input line-wise
match reader.read_line() {
Ok(line) => {
println!("message: {}", line);
}
Err(e) => {
println!("bummer dude: {}", e);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment