From: Martin Pitt Date: Tue, 1 Nov 2022 16:46:30 +0000 (+0100) Subject: warp-server: Add echo websocket route X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=05975f1d5fcc331c82f3b9786a5f4afbc027d4cd;p=learn-rust.git warp-server: Add echo websocket route --- diff --git a/warp-server/Cargo.toml b/warp-server/Cargo.toml index ffbe552..f58a15d 100644 --- a/warp-server/Cargo.toml +++ b/warp-server/Cargo.toml @@ -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" diff --git a/warp-server/src/main.rs b/warp-server/src/main.rs index a89c7a6..f4983e7 100644 --- a/warp-server/src/main.rs +++ b/warp-server/src/main.rs @@ -1,3 +1,4 @@ +use futures_util::{FutureExt, StreamExt}; use warp::Filter; #[tokio::main] @@ -7,7 +8,22 @@ async fn main() { .and(warp::header::("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; }