1
0
mirror of https://github.com/actix/examples synced 2025-02-02 09:39:03 +01:00

Implement websocket heartbeats (#48)

This commit is contained in:
sapir 2018-09-27 22:37:19 +03:00 committed by Douman
parent d9afae21b6
commit 87f89b54f0
5 changed files with 120 additions and 21 deletions

View File

@ -9,11 +9,10 @@ extern crate serde_json;
extern crate tokio_core; extern crate tokio_core;
extern crate tokio_io; extern crate tokio_io;
#[macro_use]
extern crate actix; extern crate actix;
extern crate actix_web; extern crate actix_web;
use std::time::Instant; use std::time::{Instant, Duration};
use actix::*; use actix::*;
use actix_web::server::HttpServer; use actix_web::server::HttpServer;
@ -21,6 +20,11 @@ use actix_web::{fs, http, ws, App, Error, HttpRequest, HttpResponse};
mod server; mod server;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// This is our websocket route state, this state is shared with all route /// This is our websocket route state, this state is shared with all route
/// instances via `HttpContext::state()` /// instances via `HttpContext::state()`
struct WsChatSessionState { struct WsChatSessionState {
@ -43,8 +47,8 @@ fn chat_route(req: &HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Err
struct WsChatSession { struct WsChatSession {
/// unique session id /// unique session id
id: usize, id: usize,
/// Client must send ping at least once per 10 seconds, otherwise we drop /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// connection. /// otherwise we drop connection.
hb: Instant, hb: Instant,
/// joined room /// joined room
room: String, room: String,
@ -58,6 +62,9 @@ impl Actor for WsChatSession {
/// Method is called on actor start. /// Method is called on actor start.
/// We register ws session with ChatServer /// We register ws session with ChatServer
fn started(&mut self, ctx: &mut Self::Context) { fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register // register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves // future within context, but context waits until this future resolves
// before processing any other events. // before processing any other events.
@ -102,8 +109,10 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) { fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
println!("WEBSOCKET MESSAGE: {:?}", msg); println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg { match msg {
ws::Message::Ping(msg) => ctx.pong(&msg), ws::Message::Ping(msg) => {
ws::Message::Pong(msg) => self.hb = Instant::now(), self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Text(text) => { ws::Message::Text(text) => {
let m = text.trim(); let m = text.trim();
// we check for /sss type of messages // we check for /sss type of messages
@ -173,9 +182,38 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
ws::Message::Binary(bin) => println!("Unexpected binary"), ws::Message::Binary(bin) => println!("Unexpected binary"),
ws::Message::Close(_) => { ws::Message::Close(_) => {
ctx.stop(); ctx.stop();
},
_ => (),
} }
} }
} }
impl WsChatSession {
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self, WsChatSessionState>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// notify chat server
ctx.state()
.addr
.do_send(server::Disconnect { id: act.id });
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping("");
});
}
} }
fn main() { fn main() {

View File

@ -97,6 +97,9 @@ impl ChatClient {
ctx.run_later(Duration::new(1, 0), |act, ctx| { ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.framed.write(codec::ChatRequest::Ping); act.framed.write(codec::ChatRequest::Ping);
act.hb(ctx); act.hb(ctx);
// client should also check for a timeout here, similar to the
// server code
}); });
} }
} }

View File

@ -16,17 +16,20 @@ extern crate serde_derive;
extern crate actix; extern crate actix;
extern crate actix_web; extern crate actix_web;
use std::time::Instant;
use actix::*; use actix::*;
use actix_web::server::HttpServer; use actix_web::server::HttpServer;
use actix_web::{fs, http, ws, App, Error, HttpRequest, HttpResponse}; use actix_web::{fs, http, ws, App, Error, HttpRequest, HttpResponse};
use std::time::Duration; use std::time::{Instant, Duration};
mod codec; mod codec;
mod server; mod server;
mod session; mod session;
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// This is our websocket route state, this state is shared with all route /// This is our websocket route state, this state is shared with all route
/// instances via `HttpContext::state()` /// instances via `HttpContext::state()`
struct WsChatSessionState { struct WsChatSessionState {
@ -49,8 +52,8 @@ fn chat_route(req: &HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Err
struct WsChatSession { struct WsChatSession {
/// unique session id /// unique session id
id: usize, id: usize,
/// Client must send ping at least once per 10 seconds, otherwise we drop /// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// connection. /// otherwise we drop connection.
hb: Instant, hb: Instant,
/// joined room /// joined room
room: String, room: String,
@ -112,8 +115,10 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) { fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
println!("WEBSOCKET MESSAGE: {:?}", msg); println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg { match msg {
ws::Message::Ping(msg) => ctx.pong(&msg), ws::Message::Ping(msg) => {
ws::Message::Pong(msg) => self.hb = Instant::now(), self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Text(text) => { ws::Message::Text(text) => {
let m = text.trim(); let m = text.trim();
// we check for /sss type of messages // we check for /sss type of messages
@ -183,7 +188,8 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
ws::Message::Binary(bin) => println!("Unexpected binary"), ws::Message::Binary(bin) => println!("Unexpected binary"),
ws::Message::Close(_) => { ws::Message::Close(_) => {
ctx.stop(); ctx.stop();
} },
_ => (),
} }
} }
} }
@ -191,11 +197,11 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for WsChatSession {
impl WsChatSession { impl WsChatSession {
/// helper method that sends ping to client every second. /// helper method that sends ping to client every second.
/// ///
/// also this method check heartbeats from client /// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self, WsChatSessionState>) { fn hb(&self, ctx: &mut ws::WebsocketContext<Self, WsChatSessionState>) {
ctx.run_interval(Duration::new(1, 0), |act, ctx| { ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats // check client heartbeats
if Instant::now().duration_since(act.hb) > Duration::new(10, 0) { if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out // heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!"); println!("Websocket Client heartbeat failed, disconnecting!");
@ -206,6 +212,9 @@ impl WsChatSession {
// stop actor // stop actor
ctx.stop(); ctx.stop();
// don't try to send a ping
return;
} }
ctx.ping(""); ctx.ping("");

View File

@ -74,6 +74,9 @@ impl ChatClient {
ctx.run_later(Duration::new(1, 0), |act, ctx| { ctx.run_later(Duration::new(1, 0), |act, ctx| {
act.0.ping(""); act.0.ping("");
act.hb(ctx); act.hb(ctx);
// client should also check for a timeout here, similar to the
// server code
}); });
} }
} }

View File

@ -8,22 +8,38 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
extern crate env_logger; extern crate env_logger;
use std::time::{Instant, Duration};
use actix::prelude::*; use actix::prelude::*;
use actix_web::{ use actix_web::{
fs, http, middleware, server, ws, App, Error, HttpRequest, HttpResponse, fs, http, middleware, server, ws, App, Error, HttpRequest, HttpResponse,
}; };
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
/// do websocket handshake and start `MyWebSocket` actor /// do websocket handshake and start `MyWebSocket` actor
fn ws_index(r: &HttpRequest) -> Result<HttpResponse, Error> { fn ws_index(r: &HttpRequest) -> Result<HttpResponse, Error> {
ws::start(r, MyWebSocket) ws::start(r, MyWebSocket::new())
} }
/// websocket connection is long running connection, it easier /// websocket connection is long running connection, it easier
/// to handle with an actor /// to handle with an actor
struct MyWebSocket; struct MyWebSocket {
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection.
hb: Instant,
}
impl Actor for MyWebSocket { impl Actor for MyWebSocket {
type Context = ws::WebsocketContext<Self>; type Context = ws::WebsocketContext<Self>;
/// Method is called on actor start. We start the heartbeat process here.
fn started(&mut self, ctx: &mut Self::Context) {
self.hb(ctx);
}
} }
/// Handler for `ws::Message` /// Handler for `ws::Message`
@ -32,7 +48,10 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for MyWebSocket {
// process websocket messages // process websocket messages
println!("WS: {:?}", msg); println!("WS: {:?}", msg);
match msg { match msg {
ws::Message::Ping(msg) => ctx.pong(&msg), ws::Message::Ping(msg) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Text(text) => ctx.text(text), ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin), ws::Message::Binary(bin) => ctx.binary(bin),
ws::Message::Close(_) => { ws::Message::Close(_) => {
@ -43,6 +62,33 @@ impl StreamHandler<ws::Message, ws::ProtocolError> for MyWebSocket {
} }
} }
impl MyWebSocket {
fn new() -> Self {
Self { hb: Instant::now() }
}
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut <Self as Actor>::Context) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping("");
});
}
}
fn main() { fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info"); ::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();