Skip to content

Commit d3133c0

Browse files
committed
Add TcpListener::into_incoming
1 parent f4b8c7a commit d3133c0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/net/tcp/listener.rs

+39
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,45 @@ 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+
///
171+
/// // Our server listens on multiple ports for some reason
172+
/// let listeners = vec![
173+
/// TcpListener::bind("[::0]:8080").await?,
174+
/// TcpListener::bind("[::0]:12345").await?,
175+
/// TcpListener::bind("[::0]:5678").await?,
176+
/// ];
177+
/// // Iterate over all incoming connections
178+
/// let incoming = futures::stream::select_all(
179+
/// listeners.into_iter()
180+
/// .map(TcpListener::into_incoming)
181+
/// .map(Box::pin)
182+
/// );
183+
/// #
184+
/// # Ok(()) }) }
185+
/// ```
186+
#[cfg(feature = "unstable")]
187+
pub fn into_incoming(self) -> impl Stream<Item = io::Result<TcpStream>> + Send {
188+
futures_lite::stream::unfold(self, |listener| async move {
189+
let res = listener.accept().await.map(|(stream, _)| stream);
190+
Some((res, listener))
191+
})
153192
}
154193

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

0 commit comments

Comments
 (0)