Created
May 24, 2014 18:37
-
-
Save schmichael/4589378bcee97fc7a3fb 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::io::{TcpListener, TcpStream}; | |
use std::io::{Acceptor, Listener}; | |
use std::io::BufferedStream; | |
use std::io::IoResult; | |
fn main() { | |
serve() | |
} | |
fn serve() { | |
let listener = TcpListener::bind("127.0.0.1", 8080); | |
// bind the listener to the specified address | |
let mut acceptor = listener.listen(); | |
fn handle_client(stream: TcpStream) { | |
fn err_handler(stream: TcpStream) -> IoResult<int> { | |
let mut buf_stream = BufferedStream::new(stream); | |
loop { | |
let line = try!(buf_stream.read_line()); | |
try!(buf_stream.write(line.as_bytes())); | |
try!(buf_stream.flush()) | |
} | |
} | |
match err_handler(stream) { | |
Err(e) => { | |
println!("Well that sucks: {}", e) | |
} | |
Ok(_) => {} | |
} | |
} | |
// accept connections and process them, spawning a new tasks for each one | |
for stream in acceptor.incoming() { | |
match stream { | |
Err(e) => { | |
println!("{}", e) | |
} | |
Ok(stream) => spawn(proc() { | |
// connection succeeded | |
handle_client(stream) | |
}) | |
} | |
} | |
// close the socket server | |
drop(acceptor); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment