diff --git a/src/cnf/mod.rs b/src/cnf/mod.rs index 731adbcf..5ec9a341 100644 --- a/src/cnf/mod.rs +++ b/src/cnf/mod.rs @@ -1,4 +1,5 @@ use once_cell::sync::Lazy; +use std::time::Duration; pub const LOGO: &str = " .d8888b. 888 8888888b. 888888b. @@ -21,6 +22,9 @@ pub const APP_ENDPOINT: &str = "https://surrealdb.com/app"; /// How many concurrent tasks can be handled in a WebSocket pub const MAX_CONCURRENT_CALLS: usize = 24; +/// Specifies the frequency with which ping messages should be sent to the client. +pub const WEBSOCKET_PING_FREQUENCY: Duration = Duration::from_secs(5); + /// The package identifier of this build pub const PKG_NAME: &str = env!("CARGO_PKG_NAME"); diff --git a/src/net/rpc.rs b/src/net/rpc.rs index ecd8c2a3..08b4bc67 100644 --- a/src/net/rpc.rs +++ b/src/net/rpc.rs @@ -2,6 +2,7 @@ use crate::cli::CF; use crate::cnf::MAX_CONCURRENT_CALLS; use crate::cnf::PKG_NAME; use crate::cnf::PKG_VERS; +use crate::cnf::WEBSOCKET_PING_FREQUENCY; use crate::dbs::DB; use crate::err::Error; use crate::net::session; @@ -61,6 +62,25 @@ impl Rpc { let (chn, mut rcv) = channel::new(MAX_CONCURRENT_CALLS); // Split the socket into send and recv let (mut wtx, mut wrx) = ws.split(); + // Clone the channel for sending pings + let png = chn.clone(); + // Send messages to the client + tokio::task::spawn(async move { + // Create the interval ticker + let mut interval = tokio::time::interval(WEBSOCKET_PING_FREQUENCY); + // Loop indefinitely + loop { + // Wait for the timer + interval.tick().await; + // Create the ping message + let msg = Message::ping(vec![]); + // Send the message to the client + if let Err(_) = png.send(msg).await { + // Exit out of the loop + break; + } + } + }); // Send messages to the client tokio::task::spawn(async move { // Wait for the next message to send