2017-12-02 00:24:26 -08:00
|
|
|
# WebSockets
|
2017-12-13 22:36:28 -08:00
|
|
|
|
2017-12-26 20:52:21 -08:00
|
|
|
Actix supports WebSockets out-of-the-box. It is possible to convert request's `Payload`
|
|
|
|
to a stream of [*ws::Message*](../actix_web/ws/enum.Message.html) with
|
|
|
|
a [*ws::WsStream*](../actix_web/ws/struct.WsStream.html) and then use stream
|
2018-01-13 11:17:48 -08:00
|
|
|
combinators to handle actual messages. But it is simpler to handle websocket communications
|
2017-12-26 20:52:21 -08:00
|
|
|
with http actor.
|
2017-12-13 22:36:28 -08:00
|
|
|
|
2018-01-10 10:12:34 -08:00
|
|
|
This is example of simple websocket echo server:
|
2017-12-26 20:52:21 -08:00
|
|
|
|
2018-01-10 10:12:34 -08:00
|
|
|
```rust
|
|
|
|
# extern crate actix;
|
|
|
|
# extern crate actix_web;
|
2017-12-26 20:52:21 -08:00
|
|
|
use actix::*;
|
|
|
|
use actix_web::*;
|
|
|
|
|
|
|
|
/// Define http actor
|
|
|
|
struct Ws;
|
|
|
|
|
|
|
|
impl Actor for Ws {
|
2018-01-10 10:12:34 -08:00
|
|
|
type Context = ws::WebsocketContext<Self>;
|
2017-12-26 20:52:21 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Define Handler for ws::Message message
|
2017-12-26 21:33:23 -08:00
|
|
|
impl Handler<ws::Message> for Ws {
|
2018-01-05 13:30:21 -08:00
|
|
|
type Result=();
|
2018-01-06 01:06:35 -08:00
|
|
|
|
2018-01-10 10:12:34 -08:00
|
|
|
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
|
2017-12-26 20:52:21 -08:00
|
|
|
match msg {
|
2018-01-10 10:12:34 -08:00
|
|
|
ws::Message::Ping(msg) => ctx.pong(&msg),
|
|
|
|
ws::Message::Text(text) => ctx.text(&text),
|
|
|
|
ws::Message::Binary(bin) => ctx.binary(bin),
|
2017-12-26 20:52:21 -08:00
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
Application::new()
|
2017-12-26 21:33:23 -08:00
|
|
|
.resource("/ws/", |r| r.f(|req| ws::start(req, Ws))) // <- register websocket route
|
2017-12-26 20:52:21 -08:00
|
|
|
.finish();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
Simple websocket echo server example is available in
|
|
|
|
[examples directory](https://github.com/actix/actix-web/blob/master/examples/websocket.rs).
|
|
|
|
|
|
|
|
Example chat server with ability to chat over websocket connection or tcp connection
|
|
|
|
is available in [websocket-chat directory](https://github.com/actix/actix-web/tree/master/examples/websocket-chat/)
|