Debian Codegraph @

third_party/rust/warp/examples/websockets_chat.rs

raw
1 // #![deny(warnings)]
2 use std::collections::HashMap;
3 use std::sync::{
4 atomic::{AtomicUsize, Ordering},
5 Arc,
6 };
7
8 use futures_util::{SinkExt, StreamExt, TryFutureExt};
9 use tokio::sync::{mpsc, RwLock};
10 use tokio_stream::wrappers::UnboundedReceiverStream;
11 use warp::ws::{Message, WebSocket};
12 use warp::Filter;
13
14 /// Our global unique user id counter.
15 static NEXT_USER_ID: AtomicUsize = AtomicUsize::new(1);
16
17 /// Our state of currently connected users.
18 ///
19 /// - Key is their id
20 /// - Value is a sender of `warp::ws::Message`
21 type Users = Arc<RwLock<HashMap<usize, mpsc::UnboundedSender<Message>>>>;
22
23 #[tokio::main]
24 async fn main() {
25 pretty_env_logger::init();
26
27 // Keep track of all connected users, key is usize, value
28 // is a websocket sender.
29 let users = Users::default();
30 // Turn our "state" into a new Filter...
31 let users = warp::any().map(move || users.clone());
32
33 // GET /chat -> websocket upgrade
34 let chat = warp::path("chat")
35 // The `ws()` filter will prepare Websocket handshake...
36 .and(warp::ws())
37 .and(users)
38 .map(|ws: warp::ws::Ws, users| {
39 // This will call our function if the handshake succeeds.
40 ws.on_upgrade(move |socket| user_connected(socket, users))
41 });
42
43 // GET / -> index html
44 let index = warp::path::end().map(|| warp::reply::html(INDEX_HTML));
45
46 let routes = index.or(chat);
47
48 warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
49 }
50
51 async fn user_connected(ws: WebSocket, users: Users) {
52 // Use a counter to assign a new unique ID for this user.
53 let my_id = NEXT_USER_ID.fetch_add(1, Ordering::Relaxed);
54
55 eprintln!("new chat user: {}", my_id);
56
57 // Split the socket into a sender and receive of messages.
58 let (mut user_ws_tx, mut user_ws_rx) = ws.split();
59
60 // Use an unbounded channel to handle buffering and flushing of messages
61 // to the websocket...
62 let (tx, rx) = mpsc::unbounded_channel();
63 let mut rx = UnboundedReceiverStream::new(rx);
64
65 tokio::task::spawn(async move {
66 while let Some(message) = rx.next().await {
67 user_ws_tx
68 .send(message)
69 .unwrap_or_else(|e| {
70 eprintln!("websocket send error: {}", e);
71 })
72 .await;
73 }
74 });
75
76 // Save the sender in our list of connected users.
77 users.write().await.insert(my_id, tx);
78
79 // Return a `Future` that is basically a state machine managing
80 // this specific user's connection.
81
82 // Every time the user sends a message, broadcast it to
83 // all other users...
84 while let Some(result) = user_ws_rx.next().await {
85 let msg = match result {
86 Ok(msg) => msg,
87 Err(e) => {
88 eprintln!("websocket error(uid={}): {}", my_id, e);
89 break;
90 }
91 };
92 user_message(my_id, msg, &users).await;
93 }
94
95 // user_ws_rx stream will keep processing as long as the user stays
96 // connected. Once they disconnect, then...
97 user_disconnected(my_id, &users).await;
98 }
99
100 async fn user_message(my_id: usize, msg: Message, users: &Users) {
101 // Skip any non-Text messages...
102 let msg = if let Ok(s) = msg.to_str() {
103 s
104 } else {
105 return;
106 };
107
108 let new_msg = format!("<User#{}>: {}", my_id, msg);
109
110 // New message from this user, send it to everyone else (except same uid)...
111 for (&uid, tx) in users.read().await.iter() {
112 if my_id != uid {
113 if let Err(_disconnected) = tx.send(Message::text(new_msg.clone())) {
114 // The tx is disconnected, our `user_disconnected` code
115 // should be happening in another task, nothing more to
116 // do here.
117 }
118 }
119 }
120 }
121
122 async fn user_disconnected(my_id: usize, users: &Users) {
123 eprintln!("good bye user: {}", my_id);
124
125 // Stream closed up, so remove from the user list
126 users.write().await.remove(&my_id);
127 }
128
129 static INDEX_HTML: &str = r#"<!DOCTYPE html>
130 <html lang="en">
131 <head>
132 <title>Warp Chat</title>
133 </head>
134 <body>
135 <h1>Warp chat</h1>
136 <div id="chat">
137 <p><em>Connecting...</em></p>
138 </div>
139 <input type="text" id="text" />
140 <button type="button" id="send">Send</button>
141 <script type="text/javascript">
142 const chat = document.getElementById('chat');
143 const text = document.getElementById('text');
144 const uri = 'ws://' + location.host + '/chat';
145 const ws = new WebSocket(uri);
146
147 function message(data) {
148 const line = document.createElement('p');
149 line.innerText = data;
150 chat.appendChild(line);
151 }
152
153 ws.onopen = function() {
154 chat.innerHTML = '<p><em>Connected!</em></p>';
155 };
156
157 ws.onmessage = function(msg) {
158 message(msg.data);
159 };
160
161 ws.onclose = function() {
162 chat.getElementsByTagName('em')[0].innerText = 'Disconnected!';
163 };
164
165 send.onclick = function() {
166 const msg = text.value;
167 ws.send(msg);
168 text.value = '';
169
170 message('<You>: ' + msg);
171 };
172 </script>
173 </body>
174 </html>
175 "#;