Skip to content

Commit

Permalink
Rewrite client example to modern async-std
Browse files Browse the repository at this point in the history
  • Loading branch information
skade committed Oct 30, 2019
1 parent da795de commit ef40d88
Showing 1 changed file with 27 additions and 29 deletions.
56 changes: 27 additions & 29 deletions examples/a-chat/client.rs
Original file line number Diff line number Diff line change
@@ -1,45 +1,43 @@
use futures::select;
use futures::FutureExt;
use std::sync::Arc;

use async_std::{
io::{stdin, BufReader},
net::{TcpStream, ToSocketAddrs},
prelude::*,
task,
future::select,
};


type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

pub(crate) fn main() -> Result<()> {
task::block_on(try_main("127.0.0.1:8080"))
}

async fn try_main(addr: impl ToSocketAddrs) -> Result<()> {
let stream = TcpStream::connect(addr).await?;
let (reader, mut writer) = (&stream, &stream);
let reader = BufReader::new(reader);
let mut lines_from_server = futures::StreamExt::fuse(reader.lines());

let stdin = BufReader::new(stdin());
let mut lines_from_stdin = futures::StreamExt::fuse(stdin.lines());
loop {
select! {
line = lines_from_server.next().fuse() => match line {
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(())
let stream = Arc::new(TcpStream::connect(addr).await?);
let (reader, writer) = (stream.clone(), stream.clone());

let incoming = task::spawn(async move {
let mut messages = BufReader::new(&*reader).lines();
while let Some(message) = messages.next().await {
let message = message?;
println!("{}", message);
}
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
}

0 comments on commit ef40d88

Please sign in to comment.