-
-
Save jedisct1/f24427e2a6ae8b7f6108543562744423 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
#![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; | |
extern crate tokio_proto; | |
extern crate tokio_service; | |
extern crate tokio_timer; | |
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 std::sync::Arc; | |
use std::time::Duration; | |
use std::sync::Mutex; | |
use tokio_core::reactor::Core; | |
use tokio_core::net::{TcpListener, TcpStream}; | |
use tokio_io::{AsyncRead, AsyncWrite}; | |
use tokio_io::codec::{Encoder, Decoder, Framed}; | |
use tokio_proto::pipeline::{ServerProto, ClientProto}; | |
use tokio_proto::{BindServer, TcpClient, TcpServer}; | |
use tokio_service::{NewService, Service}; | |
use tokio_timer::{Timer, Timeout}; | |
use std::collections::HashMap; | |
use std::rc::Rc; | |
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)).then(|_| Ok(())); | |
handle.spawn(server); | |
Ok(()) | |
}); | |
event_loop.handle().spawn(cnxs.map(|_| {}).map_err(|_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