]> piware.de Git - learn-rust.git/commitdiff
warp-server: Add echo websocket route
authorMartin Pitt <martin@piware.de>
Tue, 1 Nov 2022 16:46:30 +0000 (17:46 +0100)
committerMartin Pitt <martin@piware.de>
Tue, 1 Nov 2022 16:46:30 +0000 (17:46 +0100)
warp-server/Cargo.toml
warp-server/src/main.rs

index ffbe55269b2d1ba785428e2f7511ca2ec3affb46..f58a15d33ab93d61a4cbf36372c4d7dda3165dbb 100644 (file)
@@ -6,5 +6,6 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
+futures-util = { version = "0.3", default-features = false, features = ["sink"] }
 tokio = { version = "1", features = ["full"] }
 warp = "0.3"
index a89c7a6fd205e4703d04ed7f38a9232799dbd69a..f4983e73ed45895573a7ca16dbf11459a4ac0348 100644 (file)
@@ -1,3 +1,4 @@
+use futures_util::{FutureExt, StreamExt};
 use warp::Filter;
 
 #[tokio::main]
@@ -7,7 +8,22 @@ async fn main() {
         .and(warp::header::<String>("user-agent"))
         .map(|name, agent| format!("Hello, {} from {}!", name, agent));
 
-    warp::serve(hello)
+    // websocat ws://127.0.0.1:3030/ws-echo
+    let echo = warp::path("ws-echo")
+        .and(warp::ws())
+        .map(|ws: warp::ws::Ws| {
+            ws.on_upgrade(|websocket| {
+                // echo all messages back
+                let (tx, rx) = websocket.split();
+                rx.forward(tx).map(|result| {
+                    if let Err(e) = result {
+                        eprintln!("websocket error: {:?}", e);
+                    }
+                })
+            })
+        });
+
+    warp::serve(hello.or(echo))
         .run(([127, 0, 0, 1], 3030))
         .await;
 }