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()?);
|
|
|
|
|
2020-01-28 17:14:16 +00:00
|
|
|
let mut reader = stream.clone();
|
|
|
|
let mut writer = stream;
|
|
|
|
io::copy(&mut reader, &mut writer).await?;
|
2019-08-08 12:44:48 +00:00
|
|
|
|
|
|
|
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(())
|
|
|
|
})
|
|
|
|
}
|