Browse Source

Ping pong to keep websocket open

Lee Morgan 4 weeks ago
parent
commit
795027f688
1 changed files with 22 additions and 15 deletions
  1. 22 15
      src/websocket.rs

+ 22 - 15
src/websocket.rs

@@ -55,22 +55,29 @@ pub async fn listen(mut connection: Framed<BoxedSocket, Codec>) {
     let mut message_id = 1;
 
     while let Some(Ok(msg)) = connection.next().await {
-        if let Frame::Text(bytes) = msg {
-            let text = match String::from_utf8(bytes.to_vec()) {
-                Ok(t) => t,
-                Err(_) => continue
-            };
-            let parsed: Value = match from_str(&text) {
-                Ok(v) => v,
-                Err(_) => continue
-            };
-
-            if parsed["type"] == "result" {
-                println!("result");
-                println!("{:#?}", parsed);
-            }
+        match msg {
+            Frame::Text(bytes) => {
+                let text = match String::from_utf8(bytes.to_vec()) {
+                    Ok(t) => t,
+                    Err(_) => continue
+                };
+                let parsed: Value = match from_str(&text) {
+                    Ok(v) => v,
+                    Err(_) => continue
+                };
 
-            let _ = message_id;
+                if parsed["type"] == "result" {
+                    println!("result");
+                    println!("{:#?}", parsed);
+                }
+            },
+            Frame::Ping(bytes) => {
+                let _ = connection.send(Message::Pong(bytes)).await;
+            },
+            Frame::Close(reason) => {
+                println!("HA closed connection {:?}", reason);
+            },
+            _ => {}
         }
     }