1
0
mirror of https://github.com/actix/actix-website synced 2024-12-18 09:53:12 +01:00
actix-website/content/docs/websockets.cn.md
2018-06-22 23:18:14 +08:00

1.4 KiB
Raw Blame History

title menu weight
Websockets docs_proto 240

Actix支持WebSockets开箱即用。可以使用ws :: WsStream将请求的Payload转换为ws :: Message然后使用流组合器来处理实际的消息但处理websocket通信使用http actor更简单。

以下是一个简单的websocket echo server的例子

use actix::*;
use actix_web::*;

/// Define http actor
struct Ws;

impl Actor for Ws {
    type Context = ws::WebsocketContext<Self>;
}

/// Handler for ws::Message message
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {

    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() {
    App::new()
      .resource("/ws/", |r| r.f(|req| ws::start(req, Ws)))
      .finish();
}

websocket directory提供了一个简单的websocket echo server示例 。

websocket-chat directory提供了一个聊天服务器可以通过websocket或tcp连接进行聊天