Skip to content

Commit

Permalink
Fix the echo server example to prevent ConnectionClosed error (#189)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Leo1003 committed Sep 16, 2021
1 parent d566387 commit 2bfd4cd
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions examples/echo-server.rs
Expand Up @@ -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};

Expand Down Expand Up @@ -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")
}

0 comments on commit 2bfd4cd

Please sign in to comment.