Guest User

Untitled

a guest
Nov 23rd, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. extern crate futures;
  2. extern crate tokio_core;
  3. extern crate tokio_proto;
  4. extern crate tokio_service;
  5.  
  6. use std::str;
  7. use std::io::{self, ErrorKind, Write};
  8.  
  9. use futures::{future, Future, BoxFuture};
  10. use tokio_core::io::{Io, Codec, Framed, EasyBuf};
  11. use tokio_proto::TcpServer;
  12. use tokio_proto::pipeline::ServerProto;
  13. use tokio_service::Service;
  14.  
  15.  
  16. #[derive(Default)]
  17. pub struct IntCodec;
  18.  
  19. fn parse_u64(from: &[u8])-> Result<u64, io::Error> {
  20. Ok(str::from_utf8(from)
  21. .map_err(|e| io::Error::new(ErrorKind::InvalidData, e))?
  22. .parse()
  23. .map_err(|e| io::Error::new(ErrorKind::InvalidData, e))?
  24. )
  25. }
  26.  
  27. impl Codec for IntCodec {
  28. type In = u64;
  29. type Out = u64;
  30.  
  31. fn decode(&mut self, buf: &mut EasyBuf)-> Result<Option<u64>, io::Error> {
  32. println!("{:?}, 64: {:?}", buf, "64".as_bytes());
  33. if let Some(i) = buf.as_slice().iter().position(|&b| b == b'\n') {
  34. // \r\nの扱いは?
  35. let full_line = buf.drain_to(i+1);
  36.  
  37. let slice = &full_line.as_slice()[..i-1];
  38. Ok(Some(parse_u64(slice)?))
  39. } else {Ok(None)}
  40. }
  41.  
  42. fn decode_eof(&mut self, buf: &mut EasyBuf)-> io::Result<u64> {
  43. let amt = buf.len();
  44. Ok(parse_u64(buf.drain_to(amt).as_slice())?)
  45. }
  46.  
  47. fn encode(&mut self, item: u64, into: &mut Vec<u8>)-> io::Result<()> {
  48. write!(into, "{}\n", item);
  49. Ok(())
  50. }
  51. }
  52.  
  53.  
  54. pub struct IntProto;
  55.  
  56. impl<T: Io+ 'static>ServerProto<T> for IntProto {
  57. type Request = u64;
  58. type Response = u64;
  59. type Transport = Framed<T, IntCodec>;
  60. type BindTransport = Result<Self::Transport, io::Error>;
  61.  
  62. fn bind_transport(&self, io: T)-> Self::BindTransport {
  63. Ok(io.framed(IntCodec))
  64. }
  65. }
  66.  
  67.  
  68.  
  69. pub struct Doubler;
  70.  
  71. impl Service for Doubler {
  72. type Request = u64;
  73. type Response = u64;
  74. type Error = io::Error;
  75. type Future = BoxFuture<u64, io::Error>;
  76.  
  77. fn call(&self, req: u64)-> Self::Future {
  78. println!("{:?}", req);
  79. future::finished(req * 2).boxed()
  80. }
  81. }
  82.  
  83. fn main() {
  84. let addr = "127.0.0.1:8081".parse().unwrap();
  85. // This method will block the current thread until the server is shut down.
  86. TcpServer::new(IntProto, addr)
  87. .serve(|| Ok(Doubler));
  88. }
Add Comment
Please, Sign In to add comment