Skip to content

Commit 51ca48c

Browse files
committed
Add a small example for listening to both ipv4 and ipv6
Presenting stream merge on Incoming.
1 parent 177c1b6 commit 51ca48c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

examples/tcp-ipv4-and-6-echo.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//! TCP echo server, accepting connections both on both ipv4 and ipv6 sockets.
2+
//!
3+
//! To send messages, do:
4+
//!
5+
//! ```sh
6+
//! $ nc 127.0.0.1 8080
7+
//! $ nc ::1 8080
8+
//! ```
9+
10+
use async_std::io;
11+
use async_std::net::{TcpListener, TcpStream};
12+
use async_std::prelude::*;
13+
use async_std::task;
14+
15+
async fn process(stream: TcpStream) -> io::Result<()> {
16+
println!("Accepted from: {}", stream.peer_addr()?);
17+
18+
let (reader, writer) = &mut (&stream, &stream);
19+
io::copy(reader, writer).await?;
20+
21+
Ok(())
22+
}
23+
24+
fn main() -> io::Result<()> {
25+
task::block_on(async {
26+
let ipv4_listener = TcpListener::bind("127.0.0.1:8080").await?;
27+
println!("Listening on {}", ipv4_listener.local_addr()?);
28+
let ipv6_listener = TcpListener::bind("[::1]:8080").await?;
29+
println!("Listening on {}", ipv6_listener.local_addr()?);
30+
31+
let ipv4_incoming = ipv4_listener.incoming();
32+
let ipv6_incoming = ipv6_listener.incoming();
33+
34+
let mut incoming = ipv4_incoming.merge(ipv6_incoming);
35+
36+
while let Some(stream) = incoming.next().await {
37+
let stream = stream?;
38+
task::spawn(async {
39+
process(stream).await.unwrap();
40+
});
41+
}
42+
Ok(())
43+
})
44+
}

0 commit comments

Comments
 (0)