From 6af5efbf675b4513c228208ff46783a90a3f2b65 Mon Sep 17 00:00:00 2001 From: Johann150 Date: Fri, 22 Oct 2021 14:21:40 +0200 Subject: [PATCH] make process of starting listeners synchronous Alternatively, a semaphore could have been used which might be a bit faster, but since the start up process is only used once this simpler solution is not at a significant disadvantage while being much simpler. --- src/main.rs | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/src/main.rs b/src/main.rs index ccc0de6..4fe913f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -51,24 +51,27 @@ fn main() { // an error when trying to start let mut listening_unspecified = false; - let handles = ARGS.addrs.iter().map(|addr| { + let mut handles = vec![]; + for addr in &ARGS.addrs { let arc = mimetypes.clone(); - let was_listening_unspecified = listening_unspecified; - let handle = tokio::spawn(async move { - let listener = match TcpListener::bind(addr).await { - Err(e) => { - if !(addr.ip().is_unspecified() && was_listening_unspecified) { - panic!("Failed to listen on {}: {}", addr, e) - } else { - // already listening on the other unspecified address - log::warn!("Could not start listener on {}, but already listening on another unspecified address. Probably your system automatically listens in dual stack?", addr); - return; - } - } - Ok(listener) => listener, - }; + let listener = match TcpListener::bind(addr).await { + Err(e) => { + if !(addr.ip().is_unspecified() && listening_unspecified) { + panic!("Failed to listen on {}: {}", addr, e) + } else { + // already listening on the other unspecified address + log::warn!("Could not start listener on {}, but already listening on another unspecified address. Probably your system automatically listens in dual stack?", addr); + continue; + } + } + Ok(listener) => listener, + }; + listening_unspecified |= addr.ip().is_unspecified(); + + handles.push(tokio::spawn(async move { log::info!("Started listener on {}", addr); + loop { let (stream, _) = listener.accept().await.unwrap_or_else(|e| { panic!("could not accept new connection on {}: {}", addr, e) @@ -86,10 +89,8 @@ fn main() { } }); } - }); - listening_unspecified |= addr.ip().is_unspecified(); - handle - }); + })) + }; futures_util::future::join_all(handles).await; });