Last active
December 19, 2015 10:58
-
-
Save machee/5943869 to your computer and use it in GitHub Desktop.
TCP Echo Server in Rust
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
/** | |
* Rust v0.7 | |
*/ | |
extern mod extra; | |
use std::{comm, result}; | |
use extra::{net_ip, net_tcp, uv}; | |
fn main() { | |
let port = 10000; | |
// The connection is sent from the server task to the receiver task | |
// to handle the connection | |
let (receiver_port, receiver_chan) = comm::stream(); | |
let addr = net_ip::v4::parse_addr("0.0.0.0"); | |
// The server task | |
do spawn { | |
let iotask = &uv::global_loop::get(); | |
net_tcp::listen(addr, port, 128, iotask, |_| {debug!("listening");}, | |
|new_conn, kill_ch| { | |
receiver_chan.send(new_conn); | |
} | |
); | |
} | |
// Receiver task | |
do spawn { | |
loop { | |
let conn = match receiver_port.try_recv() { | |
Some(c) => c, | |
_ => break | |
}; | |
do spawn { | |
let accept_result = net_tcp::accept(conn); | |
let sock = &result::unwrap(accept_result); | |
loop { | |
let read_result = net_tcp::read(sock, 0); | |
if (!read_result.is_ok()) { | |
break; | |
} | |
let data = result::unwrap(read_result); | |
net_tcp::write(sock, data); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment