You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
async-std/examples/tcp-echo.rs

41 lines
911 B
Rust

5 years ago
//! TCP echo server.
//!
//! To send messages, do:
//!
//! ```sh
//! $ nc localhost 8080
//! ```
#![feature(async_await)]
5 years ago
use async_std::io;
5 years ago
use async_std::net::{TcpListener, TcpStream};
5 years ago
use async_std::prelude::*;
5 years ago
use async_std::task;
5 years ago
5 years ago
async fn process(stream: TcpStream) -> io::Result<()> {
5 years ago
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 {
5 years ago
let listener = TcpListener::bind("127.0.0.1:8080").await?;
5 years ago
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(())
})
}