Skip to content

Instantly share code, notes, and snippets.

@hfeeki
Forked from jfager/simple_server.rs
Last active August 29, 2015 14:11
Show Gist options
  • Save hfeeki/58ddb1cfff21a735a529 to your computer and use it in GitHub Desktop.
Save hfeeki/58ddb1cfff21a735a529 to your computer and use it in GitHub Desktop.
extern mod extra;
use std::{int,io,result};
use extra::{net,net_tcp,uv};
fn main() {
let (accept_port, accept_chan) = stream();
let (finish_port, finish_chan) = stream();
let addr = extra::net_ip::v4::parse_addr("127.0.0.1");
let port = 8080;
do spawn {
let backlog = 128;
let iotask = &uv::global_loop::get();
net::tcp::listen(addr, port, backlog, iotask,
|_| {
io::println("Init callback");
},
|conn, kill_ch| {
io::println("Listen callback");
let (res_po, res_ch) = stream::<Option<net_tcp::TcpErrData>>();
accept_chan.send((conn, res_ch));
match res_po.recv() {
Some(err_data) => kill_ch.send(Some(err_data)),
None => ()
}
});
io::println("Done listening");
finish_chan.send(());
}
do spawn {
loop {
io::println("Waiting on accept_port");
let (conn, res_ch) = accept_port.recv();
io::println("accept_port received, spawning for accept");
do std::task::spawn {
io::println("Spawned");
let accept_result = net::tcp::accept(conn);
io::println("Accepted");
match accept_result {
Err(accept_error) => {
res_ch.send(Some(accept_error));
// fail?
},
Ok(sock) => {
res_ch.send(None);
let buf = net::tcp::socket_buf(sock);
let line = buf.read_line();
io::println(fmt!("From client: %s", line));
buf.write_str("pong\n");
}
}
io::println("Accept task completed");
}
}
}
// Oops, spawning in the default scheduler.
//do spawn {
// loop {
// unsafe { std::libc::sleep(1); }
// }
//}
// Put this task in its own thread and everything works great.
do task::spawn_sched(task::ManualThreads(1)) {
loop {
io::println("herp");
unsafe { std::libc::sleep(1); }
}
}
finish_port.recv();
}
extern mod extra;
use std::{int,io,result};
use extra::{net,net_tcp,uv};
fn main() {
let addr = extra::net_ip::v4::parse_addr("127.0.0.1");
let port = 8080;
let mut counter = 0;
loop {
let iotask = &uv::global_loop::get();
let connect_result = net_tcp::connect(copy addr, port, iotask);
assert!(connect_result.is_ok());
let sock = result::unwrap(connect_result);
let buf = net_tcp::socket_buf(sock);
buf.write_str(fmt!("ping %i\n", counter));
let line = buf.read_line();
io::println(fmt!("From server: %s", line));
counter += 1;
unsafe { std::libc::sleep(1); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment