Last active
December 19, 2015 10:49
-
-
Save machee/5943794 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
/** | |
* For | |
* https://github.com/mozilla/rust/issues/3599 | |
* | |
* Based on | |
* https://github.com/mozilla/rust/blob/f19fb2459f4fc695225f996692a6a6b30b801ee9/src/libextra/flatpipes.rs#L764 | |
* | |
* Rust v0.7 | |
*/ | |
extern mod extra; | |
use std::{comm, result, int}; | |
use extra::{net_ip, net_tcp, uv}; | |
fn main() { | |
let port = 10000; | |
// Indicate to the client task that the server is listening | |
let (begin_connect_port, begin_connect_chan) = comm::stream(); | |
// The connection is sent from the server task to the receiver task | |
// to handle the connection | |
let (accept_port, accept_chan) = comm::stream(); | |
let addr = net_ip::v4::parse_addr("127.0.0.1"); | |
// The server task | |
do spawn { | |
let iotask = &uv::global_loop::get(); | |
let listen_res = net_tcp::listen(addr, port, 128, iotask, | |
|_kill_ch| { | |
debug!("listening"); | |
// Tell the sender to initiate the connection | |
begin_connect_chan.send(()) | |
}, | |
|new_conn, kill_ch| { | |
// Incoming connection. Send it to the receiver task to accept | |
let (res_port, res_chan) = comm::stream(); | |
accept_chan.send((new_conn, res_chan)); | |
// Wait until the connection is accepted | |
res_port.recv(); | |
// Stop listening | |
kill_ch.send(None) | |
} | |
); | |
assert!(listen_res.is_ok()); | |
} | |
// Client task | |
do spawn { | |
// Wait for the server to start listening | |
begin_connect_port.recv(); | |
debug!("connecting"); | |
let iotask = &uv::global_loop::get(); | |
let connect_result = net_tcp::connect(addr, port, iotask); | |
assert!(connect_result.is_ok()); | |
let sock = &result::unwrap(connect_result); | |
for int::range(0, 10) |i| { | |
debug!("sending %?", i); | |
let data: ~[u8] = ~[i as u8]; | |
net_tcp::write(sock, data); | |
} | |
debug!("stopped writing"); | |
} | |
// Receiver task | |
do spawn { | |
// Wait for a connection | |
let (conn, res_chan) = accept_port.recv(); | |
debug!("accepting connection"); | |
let accept_result = net_tcp::accept(conn); | |
debug!("accepted"); | |
assert!(accept_result.is_ok()); | |
let sock = &result::unwrap(accept_result); | |
res_chan.send(()); | |
loop { | |
let read_result = net_tcp::read(sock, 0); | |
if (!read_result.is_ok()) { | |
break; | |
} | |
let data = result::unwrap(read_result); | |
debug!("received %?", data); | |
} | |
debug!("stopped reading"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment