#rust, #actix, #actor-model, #websocket
To handle WebSocket in [Actix Framework] you need to create a WebSocket Actor. Each actor will be responsible for each connected client.
#[derive(Default)]
struct WsSession;
A WebSocket actor have a WebsocketContext
and need to implement StreamHandler
trait.
impl Actor for WsSession {
type Context = ws::WebsocketContext<Self>;
}
type WebsocketMessage = Result<ws::Message, ws::ProtocolError>;
impl StreamHandler<WebsocketMessage> for WsSession {
fn handle(&mut self, msg: WebsocketMessage, ctx: &mut Self::Context) {
...
}
}
WebsocketContext is an Actix Context that has some special features such as handling text
or binary
messages, handling ping
and pong
messages.
The handle
method of StreamHandler trait is where we process the incoming messages from the client. A ws::Message (not to be mistaken with Actor's messages) could be anything in Text or Binary or Ping/Pong.
If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.