2
0
Fork 1
mirror of https://github.com/async-rs/async-std.git synced 2025-04-23 08:46:46 +00:00

Rewrite client example to modern async-std

This commit is contained in:
Florian Gilcher 2019-10-30 19:15:29 +09:00
parent da795dec7b
commit ef40d881e9
No known key found for this signature in database
GPG key ID: E7B51D33F8EBF61B

View file

@ -1,13 +1,14 @@
use futures::select; use std::sync::Arc;
use futures::FutureExt;
use async_std::{ use async_std::{
io::{stdin, BufReader}, io::{stdin, BufReader},
net::{TcpStream, ToSocketAddrs}, net::{TcpStream, ToSocketAddrs},
prelude::*, prelude::*,
task, task,
future::select,
}; };
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
pub(crate) fn main() -> Result<()> { pub(crate) fn main() -> Result<()> {
@ -15,31 +16,28 @@ pub(crate) fn main() -> Result<()> {
} }
async fn try_main(addr: impl ToSocketAddrs) -> Result<()> { async fn try_main(addr: impl ToSocketAddrs) -> Result<()> {
let stream = TcpStream::connect(addr).await?; let stream = Arc::new(TcpStream::connect(addr).await?);
let (reader, mut writer) = (&stream, &stream); let (reader, writer) = (stream.clone(), stream.clone());
let reader = BufReader::new(reader);
let mut lines_from_server = futures::StreamExt::fuse(reader.lines());
let stdin = BufReader::new(stdin()); let incoming = task::spawn(async move {
let mut lines_from_stdin = futures::StreamExt::fuse(stdin.lines()); let mut messages = BufReader::new(&*reader).lines();
loop { while let Some(message) = messages.next().await {
select! { let message = message?;
line = lines_from_server.next().fuse() => match line { println!("{}", message);
Some(line) => {
let line = line?;
println!("{}", line);
},
None => break,
},
line = lines_from_stdin.next().fuse() => match line {
Some(line) => {
let line = line?;
writer.write_all(line.as_bytes()).await?;
writer.write_all(b"\n").await?;
}
None => break,
}
}
} }
Ok(()) Ok(())
});
let outgoing = task::spawn(async move {
let mut stdin = BufReader::new(stdin()).lines();
while let Some(line) = stdin.next().await {
let line = line?;
let message = format!("{}\n", line);
(&*writer).write_all(message.as_bytes()).await?;
}
Ok(())
});
select!(incoming, outgoing).await
} }