mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-04-24 16:42:36 +02:00
Make chat-client reads cancellation safe (#713)
* Make chat-client reads cancellation safe * Update chat-app references
This commit is contained in:
parent
8c212b3f8c
commit
4b7b5d83ea
@ -29,7 +29,7 @@ API.
|
||||
Websocket Stream.
|
||||
- [SinkExt::send()][4] implemented by `WebsocketStream`: for asynchronously
|
||||
sending messages on a Websocket Stream.
|
||||
- [BufReader::read_line()][5]: for asynchronously reading user messages
|
||||
- [Lines::next_line()][5]: for asynchronously reading user messages
|
||||
from the standard input.
|
||||
- [Sender::subscribe()][6]: for subscribing to a broadcast channel.
|
||||
|
||||
@ -104,6 +104,6 @@ $ cargo run --bin client
|
||||
[2]: https://docs.rs/tokio-websockets/0.3.2/tokio_websockets/
|
||||
[3]: https://docs.rs/tokio-websockets/0.3.2/tokio_websockets/proto/struct.WebsocketStream.html#method.next
|
||||
[4]: https://docs.rs/futures-util/0.3.28/futures_util/sink/trait.SinkExt.html#method.send
|
||||
[5]: https://docs.rs/tokio/latest/tokio/io/trait.AsyncBufReadExt.html#method.read_line
|
||||
[5]: https://docs.rs/tokio/latest/tokio/io/struct.Lines.html#method.next_line
|
||||
[6]: https://docs.rs/tokio/latest/tokio/sync/broadcast/struct.Sender.html#method.subscribe
|
||||
[7]: https://doc.rust-lang.org/cargo/reference/cargo-targets.html#binaries
|
||||
|
@ -25,12 +25,11 @@ async fn main() -> Result<(), tokio_websockets::Error> {
|
||||
.await?;
|
||||
|
||||
let stdin = tokio::io::stdin();
|
||||
let mut stdin = BufReader::new(stdin);
|
||||
let mut stdin = BufReader::new(stdin).lines();
|
||||
|
||||
// ANCHOR_END: setup
|
||||
// Continuous loop for concurrently sending and receiving messages.
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
tokio::select! {
|
||||
incoming = ws_stream.next() => {
|
||||
match incoming {
|
||||
@ -39,10 +38,10 @@ async fn main() -> Result<(), tokio_websockets::Error> {
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
res = stdin.read_line(&mut line) => {
|
||||
res = stdin.next_line() => {
|
||||
match res {
|
||||
Ok(0) => return Ok(()),
|
||||
Ok(_) => ws_stream.send(Message::text(line.trim_end().to_string())).await?,
|
||||
Ok(None) => return Ok(()),
|
||||
Ok(Some(line)) => ws_stream.send(Message::text(line.to_string())).await?,
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user