2
0
Fork 1
mirror of https://github.com/async-rs/async-std.git synced 2025-01-16 02:39:55 +00:00
async-std/examples/tcp-echo.rs

39 lines
885 B
Rust
Raw Normal View History

2019-08-08 12:44:48 +00:00
//! TCP echo server.
//!
//! To send messages, do:
//!
//! ```sh
//! $ nc localhost 8080
//! ```
2019-08-14 01:47:39 +00:00
use async_std::io;
2019-08-12 10:44:57 +00:00
use async_std::net::{TcpListener, TcpStream};
2019-08-14 01:47:39 +00:00
use async_std::prelude::*;
2019-08-14 02:22:37 +00:00
use async_std::task;
2019-08-08 12:44:48 +00:00
2019-08-12 10:44:57 +00:00
async fn process(stream: TcpStream) -> io::Result<()> {
2019-08-08 12:44:48 +00:00
println!("Accepted from: {}", stream.peer_addr()?);
let (reader, writer) = &mut (&stream, &stream);
io::copy(reader, writer).await?;
Ok(())
}
fn main() -> io::Result<()> {
task::block_on(async {
2019-08-12 10:44:57 +00:00
let listener = TcpListener::bind("127.0.0.1:8080").await?;
2019-08-08 12:44:48 +00:00
println!("Listening on {}", listener.local_addr()?);
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
let stream = stream?;
task::spawn(async {
process(stream).await.unwrap();
});
}
Ok(())
})
}