Skip to content

Commit 4c40540

Browse files
committed
Add TcpListener::into_incoming
1 parent f4b8c7a commit 4c40540

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/net/tcp/listener.rs

+38
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,44 @@ impl TcpListener {
150150
Incoming {
151151
incoming: Box::pin(self.watcher.incoming()),
152152
}
153+
}
154+
155+
/// Turn this into a stream over the connections being received on this
156+
/// listener.
157+
///
158+
/// The returned stream is infinite and will also not yield
159+
/// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
160+
/// calling [`TcpListener::accept`] in a loop.
161+
///
162+
/// ## Examples
163+
///
164+
/// Merge the incoming connections of multiple sockets into one [`Stream`]:
165+
///
166+
/// ```no_run
167+
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
168+
/// #
169+
/// use async_std::net::TcpListener;
170+
/// use async_std::prelude::*;
171+
///
172+
/// // Our server listens on multiple ports for some reason
173+
/// let listeners = vec![
174+
/// TcpListener::bind("[::0]:8080").await?,
175+
/// TcpListener::bind("[::0]:12345").await?,
176+
/// TcpListener::bind("[::0]:5678").await?,
177+
/// ];
178+
/// // Iterate over all incoming connections
179+
/// let incoming = futures::stream::select_all(
180+
/// listener.into_iter().map(TcpListener::into_incoming)
181+
/// );
182+
/// #
183+
/// # Ok(()) }) }
184+
/// ```
185+
#[cfg(unstable)]
186+
pub fn into_incoming(self) -> impl Stream<Item = io::Result<TcpStream>> + Send {
187+
std::stream::unfold(self, |listener| async move {
188+
let res = listener.accept().await.map(|(stream, _)| stream);
189+
Some((res, listener))
190+
})
153191
}
154192

155193
/// Returns the local address that this listener is bound to.

0 commit comments

Comments
 (0)