{"id":2027,"date":"2017-06-14T03:51:02","date_gmt":"2017-06-14T03:51:02","guid":{"rendered":"http:\/\/blog.zhukunqian.com\/?p=2027"},"modified":"2017-06-15T03:04:58","modified_gmt":"2017-06-15T03:04:58","slug":"rust%e5%ad%a6%e4%b9%a0%e7%ac%ac%e4%b8%80%e8%af%be","status":"publish","type":"post","link":"https:\/\/blog.zhukunqian.com\/?p=2027","title":{"rendered":"rust\u5b66\u4e60\u7b2c\u4e00\u8bfe"},"content":{"rendered":"<p>\u4f7f\u7528 tokio \u6839\u636e\u6587\u6863\u5199\u4e00\u4e2a\u6536\u53d1\u5b57\u7b26\u4e32\u5185\u5bb9\u7684tcp server.<\/p>\n<p>\u6587\u6863\u5730\u5740\uff1ahttps:\/\/tokio.rs\/docs\/getting-started\/simple-server\/<\/p>\n<pre>#[macro_use]\r\nextern crate log;\r\n\r\nextern crate bytes;\r\nextern crate tokio_io;\r\nextern crate tokio_core;\r\nextern crate tokio_proto;\r\nextern crate tokio_service;\r\nextern crate  byteorder;\r\nextern crate futures;\r\n\r\n\r\nuse std::io;\r\nuse std::str;\r\nuse std::io::Cursor;\r\nuse bytes::{BytesMut,BufMut};\r\nuse tokio_io::codec::*;\r\nuse byteorder::*;\r\nuse tokio_proto::TcpServer;\r\nuse tokio_proto::pipeline::ServerProto;\r\n\/\/use tokio_proto::multiplex::ServerProto;\r\n\/\/use tokio_proto::streaming::pipeline::ServerProto;\r\nuse tokio_io::*;\r\nuse tokio_io::codec::Framed;\r\nuse tokio_service::Service;\r\nuse futures::{future,Future,BoxFuture};\r\n\r\n#[test]\r\nfn hello(){\r\n    info!(&quot;hello&quot;);\r\n\r\n    pub struct MessageCodec;\r\n\r\n    impl Decoder for MessageCodec{\r\n        type Item=String;\r\n        type Error=io::Error;\r\n        fn decode(&amp;mut self, buf: &amp;mut BytesMut) -&gt; Result&lt;Option&lt;Self::Item&gt;, Self::Error&gt;{\r\n            println!(&quot;decode:{}&quot;,buf.len());\r\n            if buf.len()&lt;=4 {\r\n                return Ok(None);\r\n            }\r\n\r\n\r\n            let len=BigEndian::read_i32(buf.split_to(4).as_ref()) as usize;\r\n\r\n            let b=buf.split_to(len);\r\n            let content=str::from_utf8(b.as_ref());\r\n            println!(&quot;decode 2:{}&quot;,buf.len());\r\n            return Ok( Some( content.unwrap().to_owned()  ));\r\n        }\r\n    }\r\n\r\n    impl Encoder for MessageCodec{\r\n        type Item=String;\r\n        type Error=io::Error;\r\n        fn encode(&amp;mut self, item: String, buf: &amp;mut BytesMut)\r\n                  -&gt; Result&lt;(), Self::Error&gt;{\r\n            println!(&quot;encode:{}&quot;,item);\r\n            buf.put_i32::&lt;BigEndian&gt;(item.len() as i32 );\r\n            buf.put_slice(item.into_bytes().as_ref());\r\n            return Ok(());\r\n        }\r\n    }\r\n\r\n    pub struct MessageProto;\r\n\r\n    impl&lt;T:AsyncRead+AsyncWrite+&#039;static&gt; ServerProto&lt;T&gt; for MessageProto{\r\n        type Request=String;\r\n        type Response=String;\r\n        type Transport=Framed&lt;T,MessageCodec&gt;;\r\n\r\n        type BindTransport = Result&lt;Self::Transport,io::Error&gt;;\r\n        fn bind_transport(&amp;self, io: T) -&gt; Self::BindTransport{\r\n            Ok(io.framed(MessageCodec))\r\n        }\r\n    }\r\n\r\n    pub struct GameServer;\r\n\r\n    impl Service for GameServer{\r\n        \/\/\/ Requests handled by the service.\r\n        type Request=String;\r\n\r\n        \/\/\/ Responses given by the service.\r\n        type Response=String;\r\n\r\n        \/\/\/ Errors produced by the service.\r\n        type Error=io::Error;\r\n\r\n        \/\/\/ The future response value.\r\n        type Future=BoxFuture&lt;Self::Response,Self::Error  &gt;;\r\n\r\n        \/\/\/ Process the request and return the response asynchronously.\r\n        fn call(&amp;self, req: Self::Request) -&gt; Self::Future{\r\n            println!(&quot;receive:{}&quot;,req);\r\n\r\n            return future::ok(req.chars().rev().collect()).boxed();\r\n        }\r\n    }\r\n\r\n    let addr=&quot;0.0.0.0:9999&quot;.parse().unwrap();\r\n    let server=TcpServer::new(MessageProto,addr);\r\n\r\n    println!(&quot;start running&quot;);\r\n    server.serve(|| Ok(GameServer));\r\n\r\n    println!(&quot;hello test&quot;);\r\n}<\/pre>\n<p>\u7b2c\u4e00\u6b21\u57fa\u7840\u4e0a\u7b97\u6b63\u89c4\u7684\u8fb9\u770b\u6587\u6863\uff0c\u8fb9\u5199\uff0c\u8fb9\u7406\u89e3\u8bed\u6cd5\uff0c\u8fb9google\u3002<\/p>\n<p>\u8fc7\u7a0b\u4e2d\u638c\u63e1\u4ee5\u4e0b\u77e5\u8bc6\u70b9\uff1a<\/p>\n<pre class=\"brush: bash; gutter: true\">1\u3001\u7c7b\u578b\u8f6c\u6362\r\ni32 \u8f6c\u4e3a u32\r\na as u32\r\n2\u3001\u4ece [u8] \u4e2d\u8bfb\u53d6\u4e00\u4e2a\u57fa\u7840\u7c7b\u578b\r\nBigEndian::read_i32(buf)\r\n3\u3001byte[] \u8f6c\u4e3a\u5b57\u7b26\u4e32\r\n       str::from_utf8([u8])\r\n4\u3001\u5b57\u7b26\u4e32\u8f6c\u4e3abytes\r\nstr.into_bytes()\r\n5\u3001slice\u76ee\u524dide\u65e0\u6cd5\u505a\u5230\u667a\u80fd\u8bed\u6cd5\u63d0\u793a\u3002\r\n       \u9700\u8981\u81ea\u5df1\u6765\u5904\u7406\u3002\r\n6\u3001bytes\u53d6\u4e00\u4e2aslice\u518d\u8f6c\u4e3abyte[]\r\n       buf[a..b].as_ref()<\/pre>\n<p>\u4e0b\u4e00\u6b65\u5c31\u662f\u81ea\u5df1\u7528tcpstream\u53bb\u8fde\u4e0a\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4f7f\u7528 tokio \u6839\u636e\u6587\u6863\u5199\u4e00\u4e2a\u6536\u53d1\u5b57\u7b26\u4e32\u5185\u5bb9\u7684tcp server. \u6587\u6863\u5730\u5740 &hellip;<\/p>\n<p class=\"read-more\"><a href=\"https:\/\/blog.zhukunqian.com\/?p=2027\">\u7ee7\u7eed\u9605\u8bfb &raquo;<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32],"tags":[],"_links":{"self":[{"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/posts\/2027"}],"collection":[{"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2027"}],"version-history":[{"count":3,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/posts\/2027\/revisions"}],"predecessor-version":[{"id":2030,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=\/wp\/v2\/posts\/2027\/revisions\/2030"}],"wp:attachment":[{"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2027"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2027"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.zhukunqian.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2027"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}