@@ -2,6 +2,7 @@ use std::collections::{HashMap, VecDeque};
22use std:: error:: Error ;
33use std:: net:: SocketAddr ;
44use std:: sync:: Arc ;
5+ use std:: time:: { Duration , Instant } ;
56
67use futures:: StreamExt ;
78use tokio:: io;
@@ -163,6 +164,7 @@ struct PeerHandle {
163164struct Peer {
164165 id : String ,
165166 room_id : Option < u32 > ,
167+ last_heartbeat : Instant ,
166168 addr : SocketAddr ,
167169 stream : FrameStream ,
168170 rx : Rx , // mpsc channel used to receive messages from peers
@@ -189,6 +191,7 @@ impl Peer {
189191 Ok ( Peer {
190192 id,
191193 room_id : None ,
194+ last_heartbeat : Instant :: now ( ) ,
192195 addr,
193196 stream,
194197 rx,
@@ -277,10 +280,19 @@ async fn handle_handshaken_connection(
277280 return handle_authenticated_connection ( state, stream, id, name) . await ;
278281 }
279282
280- _ => return Err ( "not allowed" . into ( ) ) ,
283+ _ => {
284+ println ! ( "not allowed request was {:?}" , request) ;
285+ return Err ( "not allowed" . into ( ) ) ;
286+ }
281287 } ,
282288
283- _ => return Err ( "not allowed" . into ( ) ) ,
289+ // sure
290+ Message :: Heartbeat => { }
291+
292+ _ => {
293+ println ! ( "not allowed message was {:?}" , msg) ;
294+ return Err ( "not allowed" . into ( ) ) ;
295+ }
284296 }
285297 }
286298
@@ -362,6 +374,8 @@ async fn handle_authenticated_connection(
362374 // create a new Peer
363375 let mut peer = Peer :: new ( state. clone ( ) , stream, id, name) . await ?;
364376
377+ let mut heartbeat_check_interval = tokio:: time:: interval ( tokio:: time:: Duration :: from_secs ( 10 ) ) ;
378+
365379 // process incoming messages until disconnected
366380 loop {
367381 tokio:: select! {
@@ -387,6 +401,14 @@ async fn handle_authenticated_connection(
387401 // socket disconnected
388402 None => break
389403 } ,
404+
405+ // if we haven't received a heartbeat in the last 2 minutes, disconnect them
406+ _ = heartbeat_check_interval. tick( ) => {
407+ let elapsed = peer. last_heartbeat. elapsed( ) ;
408+ if elapsed > Duration :: from_secs( 120 ) {
409+ break
410+ }
411+ }
390412 }
391413 }
392414
@@ -487,6 +509,11 @@ async fn handle_message(
487509 Ok ( ( ) )
488510 }
489511
512+ Message :: Heartbeat => {
513+ peer. last_heartbeat = Instant :: now ( ) ;
514+ Ok ( ( ) )
515+ }
516+
490517 // should not be reached
491518 Message :: QueryRoomList => Ok ( ( ) ) ,
492519 Message :: Notification ( _) => Ok ( ( ) ) ,
0 commit comments