From da082eacbc111099ff2437484ccbf58c2432d39a Mon Sep 17 00:00:00 2001 From: boxdot Date: Tue, 4 Jun 2024 10:53:38 +0200 Subject: [PATCH] Robust server example (#11) This handles connection errors. The server example does not exit anymore, instead it reports them to stderr. Closes #7 --- examples/helloworld/src/server.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/examples/helloworld/src/server.rs b/examples/helloworld/src/server.rs index a305dba..c5ecc3d 100644 --- a/examples/helloworld/src/server.rs +++ b/examples/helloworld/src/server.rs @@ -36,13 +36,19 @@ async fn main() -> Result<(), Box> { let listener = TcpListener::bind(addr).await?; let listener_stream = TcpListenerStream::new(listener); - let incoming = listener_stream.then(|connection| async { + let incoming = listener_stream.filter_map(|connection| async { match connection { Ok(tcp_stream) => { - let ws_stream = tokio_tungstenite::accept_async(tcp_stream).await.unwrap(); - Ok(WsConnection::from_combined_channel(ws_stream)) + let ws_stream = match tokio_tungstenite::accept_async(tcp_stream).await { + Ok(ws_stream) => ws_stream, + Err(e) => { + eprintln!("failed to accept connection: {e}"); + return None; + } + }; + Some(Ok(WsConnection::from_combined_channel(ws_stream))) } - Err(e) => Err(e), + Err(e) => Some(Err(e)), } });