|
| 1 | + |
| 2 | +## All Together |
| 3 | + |
| 4 | +At this point, we only need to start broker to get a fully-functioning (in the happy case!) chat: |
| 5 | + |
| 6 | +```rust |
| 7 | +#![feature(async_await)] |
| 8 | + |
| 9 | +use std::{ |
| 10 | + net::ToSocketAddrs, |
| 11 | + sync::Arc, |
| 12 | + collections::hash_map::{HashMap, Entry}, |
| 13 | +}; |
| 14 | + |
| 15 | +use futures::{ |
| 16 | + channel::mpsc, |
| 17 | + SinkExt, |
| 18 | +}; |
| 19 | + |
| 20 | +use async_std::{ |
| 21 | + io::BufReader, |
| 22 | + prelude::*, |
| 23 | + task, |
| 24 | + net::{TcpListener, TcpStream}, |
| 25 | +}; |
| 26 | + |
| 27 | +type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>; |
| 28 | +type Sender<T> = mpsc::UnboundedSender<T>; |
| 29 | +type Receiver<T> = mpsc::UnboundedReceiver<T>; |
| 30 | + |
| 31 | + |
| 32 | +fn main() -> Result<()> { |
| 33 | + task::block_on(server("127.0.0.1:8080")) |
| 34 | +} |
| 35 | + |
| 36 | +async fn server(addr: impl ToSocketAddrs) -> Result<()> { |
| 37 | + let listener = TcpListener::bind(addr).await?; |
| 38 | + |
| 39 | + let (broker_sender, broker_receiver) = mpsc::unbounded(); // 1 |
| 40 | + let _broker_handle = task::spawn(broker(broker_receiver)); |
| 41 | + let mut incoming = listener.incoming(); |
| 42 | + while let Some(stream) = incoming.next().await { |
| 43 | + let stream = stream?; |
| 44 | + println!("Accepting from: {}", stream.peer_addr()?); |
| 45 | + spawn_and_log_error(client(broker_sender.clone(), stream)); |
| 46 | + } |
| 47 | + Ok(()) |
| 48 | +} |
| 49 | + |
| 50 | +async fn client(mut broker: Sender<Event>, stream: TcpStream) -> Result<()> { |
| 51 | + let stream = Arc::new(stream); // 2 |
| 52 | + let reader = BufReader::new(&*stream); |
| 53 | + let mut lines = reader.lines(); |
| 54 | + |
| 55 | + let name = match lines.next().await { |
| 56 | + None => Err("peer disconnected immediately")?, |
| 57 | + Some(line) => line?, |
| 58 | + }; |
| 59 | + broker.send(Event::NewPeer { name: name.clone(), stream: Arc::clone(&stream) }).await // 3 |
| 60 | + .unwrap(); |
| 61 | + |
| 62 | + while let Some(line) = lines.next().await { |
| 63 | + let line = line?; |
| 64 | + let (dest, msg) = match line.find(':') { |
| 65 | + None => continue, |
| 66 | + Some(idx) => (&line[..idx], line[idx + 1 ..].trim()), |
| 67 | + }; |
| 68 | + let dest: Vec<String> = dest.split(',').map(|name| name.trim().to_string()).collect(); |
| 69 | + let msg: String = msg.trim().to_string(); |
| 70 | + |
| 71 | + broker.send(Event::Message { // 4 |
| 72 | + from: name.clone(), |
| 73 | + to: dest, |
| 74 | + msg, |
| 75 | + }).await.unwrap(); |
| 76 | + } |
| 77 | + Ok(()) |
| 78 | +} |
| 79 | + |
| 80 | +async fn client_writer( |
| 81 | + mut messages: Receiver<String>, |
| 82 | + stream: Arc<TcpStream>, |
| 83 | +) -> Result<()> { |
| 84 | + let mut stream = &*stream; |
| 85 | + while let Some(msg) = messages.next().await { |
| 86 | + stream.write_all(msg.as_bytes()).await?; |
| 87 | + } |
| 88 | + Ok(()) |
| 89 | +} |
| 90 | + |
| 91 | +#[derive(Debug)] |
| 92 | +enum Event { |
| 93 | + NewPeer { |
| 94 | + name: String, |
| 95 | + stream: Arc<TcpStream>, |
| 96 | + }, |
| 97 | + Message { |
| 98 | + from: String, |
| 99 | + to: Vec<String>, |
| 100 | + msg: String, |
| 101 | + }, |
| 102 | +} |
| 103 | + |
| 104 | +async fn broker(mut events: Receiver<Event>) -> Result<()> { |
| 105 | + let mut peers: HashMap<String, Sender<String>> = HashMap::new(); |
| 106 | + |
| 107 | + while let Some(event) = events.next().await { |
| 108 | + match event { |
| 109 | + Event::Message { from, to, msg } => { |
| 110 | + for addr in to { |
| 111 | + if let Some(peer) = peers.get_mut(&addr) { |
| 112 | + peer.send(format!("from {}: {}\n", from, msg)).await? |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + Event::NewPeer { name, stream} => { |
| 117 | + match peers.entry(name) { |
| 118 | + Entry::Occupied(..) => (), |
| 119 | + Entry::Vacant(entry) => { |
| 120 | + let (client_sender, client_receiver) = mpsc::unbounded(); |
| 121 | + entry.insert(client_sender); // 4 |
| 122 | + spawn_and_log_error(client_writer(client_receiver, stream)); // 5 |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + Ok(()) |
| 129 | +} |
| 130 | +``` |
| 131 | + |
| 132 | +1. Inside the `server`, we create broker's channel and `task`. |
| 133 | +2. Inside `client`, we need to wrap `TcpStream` into an `Arc`, to be able to share it with the `client_writer`. |
| 134 | +3. On login, we notify the broker. |
| 135 | + Note that we `.unwrap` on send: broker should outlive all the clients and if that's not the case the broker probably panicked, so we can escalate the panic as well. |
| 136 | +4. Similarly, we forward parsed messages to the broker, assuming that it is alive. |
0 commit comments