Last active
August 24, 2016 10:48
-
-
Save pyfisch/eae6d84873c6f1b8b8e95b1d650bd31e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extern crate tokio; | |
use std::io; | |
use std::ops::Range; | |
use tokio::io::{TryRead, TryWrite}; | |
use tokio::server::listen; | |
use tokio::tcp::TcpStream; | |
use tokio::reactor::{Reactor, Task, Tick}; | |
struct Echo { | |
buf: Vec<u8>, | |
pending: Range<usize>, | |
stream: TcpStream, | |
} | |
impl Echo { | |
fn from_stream(stream: TcpStream) -> io::Result<Echo> { | |
Ok(Echo { | |
buf: vec![0; 128], | |
pending: 0..0, | |
stream: stream, | |
}) | |
} | |
} | |
impl Task for Echo { | |
fn tick(&mut self) -> io::Result<Tick> { | |
loop { | |
match self.pending { | |
Range { start, end } if start == end => { | |
if let Some(len) = try!(self.stream | |
.try_read(&mut self.buf)) { | |
self.pending = 0..len; | |
} else { | |
return Ok(Tick::WouldBlock); | |
} | |
} | |
ref mut range => { | |
if let Some(len) = try!(self.stream | |
.try_write(&self.buf[range.clone()])) { | |
range.start += len; | |
} else { | |
return Ok(Tick::WouldBlock); | |
} | |
} | |
} | |
} | |
} | |
} | |
fn main() { | |
let reactor = Reactor::default().unwrap(); | |
let address = "0.0.0.0:7000".parse().unwrap(); | |
listen(&reactor.handle(), address, Echo::from_stream).unwrap(); | |
reactor.run().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment