Handlers

First, we will implement a StreamHandler instance of the ws::Message messages:

impl StreamHandler<Message, ProtocolError> for NotifyActor {
fn handle(&mut self, msg: Message, ctx: &mut Self::Context) {
match msg {
Message::Ping(msg) => {
self.last_ping = Instant::now();
ctx.pong(&msg);
}
Message::Pong(_) => {
self.last_ping = Instant::now();
}
Message::Text(_) => { },
Message::Binary(_) => { },
Message::Close(_) => {
ctx.stop();
}
}
}
}

This is a basic approach for implementing the WebSocket protocol interaction with actix-web. We will use the ws::start method later to attach a Stream of WebSocket messages to this actor.

The Message type has multiple variants that reflects types of WebSocket messages from RFC 6455 (the official protocol specification). We use Ping and Pong to update the last_ping field of the actor's struct, and use Close to stop the connection by user's demand.

The last Handler we have to implement allows us to receive RepeaterUpdate messages and to send NewComment values to a client:

impl Handler<RepeaterUpdate> for NotifyActor {
type Result = ();

fn handle(&mut self, msg: RepeaterUpdate, ctx: &mut Self::Context) -> Self::Result {
let RepeaterUpdate(comment) = msg;
if let Ok(data) = serde_json::to_string(&comment) {
ctx.text(data);
}
}
}

The implementation destructs a RepeaterUpdate message to get a NewComment value, serializes it to JSON using the serde_json crate, and sends it to a client using the text method of WebsocketContext.

We have all necessary actors, so let's join them with a server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.151