1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/// Published example from `smol crate`. See also `demo/smol_chat_server.rs` and
/// `demo/smol_chat_server_profile.rs`.
//# Purpose: Demo, and participant in `thag_profiler` test.
//# Categories: demo
// A TCP chat client.
//
// First start a server:
//
// ```
// cargo run --example chat-server
// ```
//
// Then start clients:
//
// ```
// cargo run --example chat-client
// ```
use std::net::TcpStream;
use smol::{future, io, Async, Unblock};
fn main() -> io::Result<()> {
smol::block_on(async {
// Connect to the server and create async stdin and stdout.
let stream = Async::<TcpStream>::connect(([127, 0, 0, 1], 6000)).await?;
let stdin = Unblock::new(std::io::stdin());
let mut stdout = Unblock::new(std::io::stdout());
// Intro messages.
println!("Connected to {}", stream.get_ref().peer_addr()?);
println!("My nickname: {}", stream.get_ref().local_addr()?);
println!("Type a message and hit enter!\n");
let reader = &stream;
let mut writer = &stream;
// Wait until the standard input is closed or the connection is closed.
future::race(
async {
let res = io::copy(stdin, &mut writer).await;
println!("Quit!");
res
},
async {
let res = io::copy(reader, &mut stdout).await;
println!("Server disconnected!");
res
},
)
.await?;
Ok(())
})
}