From 2f97a9f8f7621dcabe08c89b0f4470e00df55440 Mon Sep 17 00:00:00 2001 From: Henrik Lievonen Date: Tue, 9 Feb 2021 02:07:31 +0200 Subject: [PATCH] Allow construction of websocket pong messages (#800) Fixes #782 --- src/filters/ws.rs | 11 +++++++++++ tests/ws.rs | 22 ++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/filters/ws.rs b/src/filters/ws.rs index 956cfe4ea..2bf79a20a 100644 --- a/src/filters/ws.rs +++ b/src/filters/ws.rs @@ -291,6 +291,17 @@ impl Message { } } + /// Construct a new Pong `Message`. + /// + /// Note that one rarely needs to manually construct a Pong message because the underlying tungstenite socket + /// automatically responds to the Ping messages it receives. Manual construction might still be useful in some cases + /// like in tests or to send unidirectional heartbeats. + pub fn pong>>(v: V) -> Message { + Message { + inner: protocol::Message::Pong(v.into()), + } + } + /// Construct the default Close `Message`. pub fn close() -> Message { Message { diff --git a/tests/ws.rs b/tests/ws.rs index 052a195f4..1667da927 100644 --- a/tests/ws.rs +++ b/tests/ws.rs @@ -149,6 +149,28 @@ async fn echo_pings() { assert_eq!(msg.as_bytes(), &b"clt"[..]); } +#[tokio::test] +async fn pongs_only() { + let _ = pretty_env_logger::try_init(); + + let mut client = warp::test::ws() + .handshake(ws_echo()) + .await + .expect("handshake"); + + // construct a pong message and make sure it is correct + let msg = Message::pong("clt"); + assert!(msg.is_pong()); + assert_eq!(msg.as_bytes(), &b"clt"[..]); + + // send it to echo and wait for `ws_echo` to send it back + client.send(msg).await; + + let msg = client.recv().await.expect("recv"); + assert!(msg.is_pong()); + assert_eq!(msg.as_bytes(), &b"clt"[..]); +} + #[tokio::test] async fn closed() { let _ = pretty_env_logger::try_init();