Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created March 23, 2017 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jedisct1/e7eaa5649d37bb3eebb5a61e6d270c7e to your computer and use it in GitHub Desktop.
Save jedisct1/e7eaa5649d37bb3eebb5a61e6d270c7e to your computer and use it in GitHub Desktop.
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
use bytes::{BytesMut, Bytes};
use futures::{future, Future, BoxFuture, Stream, Sink};
use std::cell::RefCell;
use std::io;
use std::io::{Read, Write};
use std::str;
use tokio_core::reactor::Core;
use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Encoder, Decoder, Framed};
pub type BoxIoFuture<T> = Box<Future<Item = T, Error = io::Error>>;
pub struct LineCodec;
impl Decoder for LineCodec {
type Item = String;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<Self::Item>> {
println!("decode");
if let Some(i) = buf.iter().position(|&x| x == b'\n') {
let line = buf.split_to(i);
buf.split_to(1);
Ok(Some(str::from_utf8(&line).unwrap().to_string()))
} else {
Ok(None)
}
}
}
impl Encoder for LineCodec {
type Item = String;
type Error = io::Error;
fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> io::Result<()> {
buf.extend(msg.as_bytes());
buf.extend(b"\n");
Ok(())
}
}
struct Tokio3;
impl Tokio3 {
fn main(&self) {
let mut event_loop = Core::new().unwrap();
let handle = event_loop.handle();
let addr = "0.0.0.0:12345".parse().unwrap();
let listener = TcpListener::bind(&addr, &handle).unwrap();
let incoming = listener.incoming();
let cnxs = incoming.for_each(move |(stream, addr)| {
let (writer, mut reader) = stream.framed(LineCodec)
.split();
let server = reader.and_then(|x| writer.send(x));
handle.spawn(server);
Ok(())
});
event_loop.handle().spawn(cnxs.map(|_| {}).map_err(|_| {}));
loop {
event_loop.turn(None)
}
}
}
pub fn main() {
let tokio3 = Tokio3;
tokio3.main();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment