1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-25 00:12:59 +01:00
actix-extras/guide/src/qs_9.md

50 lines
1.5 KiB
Markdown
Raw Normal View History

2017-12-02 09:24:26 +01:00
# WebSockets
2017-12-14 07:36:28 +01: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 20:17:48 +01:00
combinators to handle actual messages. But it is simpler to handle websocket communications
with http actor.
2017-12-14 07:36:28 +01:00
This is example of simple websocket echo server:
```rust
# extern crate actix;
# extern crate actix_web;
use actix::*;
use actix_web::*;
/// Define http actor
struct Ws;
impl Actor for Ws {
type Context = ws::WebsocketContext<Self>;
}
/// Define Handler for ws::Message message
2017-12-27 06:33:23 +01:00
impl Handler<ws::Message> for Ws {
2018-01-05 22:30:21 +01:00
type Result=();
2018-01-06 10:06:35 +01:00
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
match msg {
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(&text),
ws::Message::Binary(bin) => ctx.binary(bin),
_ => (),
}
}
}
fn main() {
Application::new()
2017-12-27 06:33:23 +01:00
.resource("/ws/", |r| r.f(|req| ws::start(req, Ws))) // <- register websocket route
.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/)