From 451d642039db9ae630ae8897f050ffd68751c8db Mon Sep 17 00:00:00 2001 From: Leo Date: Sat, 11 Sep 2021 04:09:40 +0800 Subject: [PATCH] Fix the echo server example to prevent ConnectionClosed error Related #188 The echo server would generate ConnectionClosed error when the peer close the connection normally. This is because that `tungstenite` crate automatically reply Close message to the peer. Then StreamExt::forward() also forwards the Close message after the connection is closed. --- examples/echo-server.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/examples/echo-server.rs b/examples/echo-server.rs index 2cb4f5f..3fef271 100644 --- a/examples/echo-server.rs +++ b/examples/echo-server.rs @@ -10,7 +10,7 @@ use std::{env, io::Error}; -use futures_util::StreamExt; +use futures_util::{future, StreamExt, TryStreamExt}; use log::info; use tokio::net::{TcpListener, TcpStream}; @@ -42,5 +42,9 @@ async fn accept_connection(stream: TcpStream) { info!("New WebSocket connection: {}", addr); let (write, read) = ws_stream.split(); - read.forward(write).await.expect("Failed to forward message") + // We should not forward messages other than text or binary. + read.try_filter(|msg| future::ready(msg.is_text() || msg.is_binary())) + .forward(write) + .await + .expect("Failed to forward messages") }