From 71dc9edf8e7e092f02621dd60469a96e742060d8 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Fri, 20 Oct 2017 21:08:38 -0700 Subject: [PATCH] add simple websocket example --- examples/websocket-chat/client.py | 32 ---------- examples/websocket/Cargo.toml | 12 ++++ examples/websocket/src/main.rs | 73 ++++++++++++++++++++++ examples/websocket/static/index.html | 90 ++++++++++++++++++++++++++++ src/server.rs | 4 +- src/staticfiles.rs | 4 +- src/ws.rs | 2 +- 7 files changed, 181 insertions(+), 36 deletions(-) delete mode 100644 examples/websocket-chat/client.py create mode 100644 examples/websocket/Cargo.toml create mode 100644 examples/websocket/src/main.rs create mode 100644 examples/websocket/static/index.html diff --git a/examples/websocket-chat/client.py b/examples/websocket-chat/client.py deleted file mode 100644 index 35f97c1a..00000000 --- a/examples/websocket-chat/client.py +++ /dev/null @@ -1,32 +0,0 @@ -import asyncio -import aiohttp - - -def req1(): - with aiohttp.MultipartWriter() as writer: - writer.append('test') - writer.append_json({'passed': True}) - - resp = yield from aiohttp.request( - "post", 'http://localhost:8080/multipart', - data=writer, headers=writer.headers) - print(resp) - assert 200 == resp.status - - -def req2(): - with aiohttp.MultipartWriter() as writer: - writer.append('test') - writer.append_json({'passed': True}) - writer.append(open('src/main.rs')) - - resp = yield from aiohttp.request( - "post", 'http://localhost:8080/multipart', - data=writer, headers=writer.headers) - print(resp) - assert 200 == resp.status - - -loop = asyncio.get_event_loop() -loop.run_until_complete(req1()) -loop.run_until_complete(req2()) diff --git a/examples/websocket/Cargo.toml b/examples/websocket/Cargo.toml new file mode 100644 index 00000000..33d9ed39 --- /dev/null +++ b/examples/websocket/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "websocket-example" +version = "0.1.0" +authors = ["Nikolay Kim "] + +[[bin]] +name = "websocket" +path = "src/main.rs" + +[dependencies] +actix = { git = "https://github.com/fafhrd91/actix.git" } +actix-web = { path = "../../" } diff --git a/examples/websocket/src/main.rs b/examples/websocket/src/main.rs new file mode 100644 index 00000000..af7b33ef --- /dev/null +++ b/examples/websocket/src/main.rs @@ -0,0 +1,73 @@ +#![allow(unused_variables)] +extern crate actix; +extern crate actix_web; + +use actix::*; +use actix_web::*; + + +struct MyWebSocket; + +impl Actor for MyWebSocket { + type Context = HttpContext; +} + +impl Route for MyWebSocket { + type State = (); + + fn request(req: HttpRequest, payload: Payload, ctx: &mut HttpContext) -> Reply + { + match ws::handshake(&req) { + Ok(resp) => { + ctx.start(resp); + ctx.add_stream(ws::WsStream::new(payload)); + Reply::async(MyWebSocket) + } + Err(err) => { + Reply::reply(err) + } + } + } +} + +impl ResponseType for MyWebSocket { + type Item = (); + type Error = (); +} + +impl StreamHandler for MyWebSocket {} + +impl Handler for MyWebSocket { + fn handle(&mut self, msg: ws::Message, ctx: &mut HttpContext) + -> Response + { + println!("WS: {:?}", msg); + match msg { + ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, msg), + ws::Message::Text(text) => ws::WsWriter::text(ctx, &text), + ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin), + ws::Message::Closed | ws::Message::Error => { + ctx.stop(); + } + _ => (), + } + Self::empty() + } +} + + +fn main() { + let sys = actix::System::new("ws-example"); + + HttpServer::new( + RoutingMap::default() + .resource("/ws/", |r| r.get::()) + .app("/", Application::default() + .route_handler("/", StaticFiles::new("static/", true)) + .finish()) + .finish()) + .serve::<_, ()>("127.0.0.1:8080").unwrap(); + + println!("Started http server: 127.0.0.1:8080"); + let _ = sys.run(); +} diff --git a/examples/websocket/static/index.html b/examples/websocket/static/index.html new file mode 100644 index 00000000..e59e13f1 --- /dev/null +++ b/examples/websocket/static/index.html @@ -0,0 +1,90 @@ + + + + + + + + +

Chat!

+
+  | Status: + disconnected +
+
+
+
+ + +
+ + diff --git a/src/server.rs b/src/server.rs index 88848649..cf6ae8bc 100644 --- a/src/server.rs +++ b/src/server.rs @@ -148,11 +148,11 @@ pub struct HttpChannel { keepalive_timer: Option, } -impl Drop for HttpChannel { +/*impl Drop for HttpChannel { fn drop(&mut self) { println!("Drop http channel"); } -} +}*/ impl Actor for HttpChannel where T: AsyncRead + AsyncWrite + 'static, A: 'static diff --git a/src/staticfiles.rs b/src/staticfiles.rs index 2b6ea65b..b22c150e 100644 --- a/src/staticfiles.rs +++ b/src/staticfiles.rs @@ -129,7 +129,9 @@ impl StaticFiles { impl RouteHandler for StaticFiles { fn set_prefix(&mut self, prefix: String) { - self.prefix += &prefix; + if prefix != "/" { + self.prefix += &prefix; + } } fn handle(&self, req: HttpRequest, payload: Payload, state: Rc) -> Task { diff --git a/src/ws.rs b/src/ws.rs index 5560a46b..c8baf885 100644 --- a/src/ws.rs +++ b/src/ws.rs @@ -49,7 +49,7 @@ //! { //! match msg { //! ws::Message::Ping(msg) => ws::WsWriter::pong(ctx, msg), -//! ws::Message::Text(text) => ws::WsWriter::text(ctx, text), +//! ws::Message::Text(text) => ws::WsWriter::text(ctx, &text), //! ws::Message::Binary(bin) => ws::WsWriter::binary(ctx, bin), //! _ => (), //! }