Skip to content
Myr

client.rs

This file

Path

examples/websockets/src/client.rs

159 lines · 5.4 KiB · Rust

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than dcbcf5c point at it.

axum-extra: Make typed-routing feature enable routing feature (#3514)tottotobefore adoptiondcbcf5c

lines 1–159why, one step back
1//! Based on tokio-tungstenite example websocket client, but with multiple
2//! concurrent websocket clients in one package3//!4//! This will connect to a server specified in the SERVER with N_CLIENTS5//! concurrent connections, and then flood some test messages over websocket.6//! This will also print whatever it gets into stdout.7//!8//! Note that this is not currently optimized for performance, especially around9//! stdout mutex management. Rather it's intended to show an example of working with axum's10//! websocket server and how the client-side and server-side code can be quite similar.11//!1213use futures_util::{SinkExt, StreamExt};14use std::ops::ControlFlow;15use std::time::Instant;16use tokio::task::JoinSet;17use tokio_tungstenite::tungstenite::Utf8Bytes;1819// we will use tungstenite for websocket client impl (same library as what axum is using)20use tokio_tungstenite::{21 connect_async,22 tungstenite::protocol::{frame::coding::CloseCode, CloseFrame, Message},23};2425const N_CLIENTS: usize = 2; //set to desired number26const SERVER: &str = "ws://127.0.0.1:3000/ws";2728#[tokio::main]29async fn main() {30 let start_time = Instant::now();31 //spawn several clients that will concurrently talk to the server32 let mut clients = (0..N_CLIENTS).map(spawn_client).collect::<JoinSet<_>>();3334 //wait for all our clients to exit35 while clients.join_next().await.is_some() {}3637 let end_time = Instant::now();3839 //total time should be the same no matter how many clients we spawn40 println!(41 "Total time taken {:#?} with {N_CLIENTS} concurrent clients, should be about 6.45 seconds.",42 end_time - start_time43 );44}4546//creates a client. quietly exits on failure.47async fn spawn_client(who: usize) {48 let ws_stream = match connect_async(SERVER).await {49 Ok((stream, response)) => {50 println!("Handshake for client {who} has been completed");51 // This will be the HTTP response, same as with server this is the last moment we52 // can still access HTTP stuff.53 println!("Server response was {response:?}");54 stream55 }56 Err(e) => {57 println!("WebSocket handshake for client {who} failed with {e}!");58 return;59 }60 };6162 let (mut sender, mut receiver) = ws_stream.split();6364 //we can ping the server for start65 sender66 .send(Message::Ping(axum::body::Bytes::from_static(67 b"Hello, Server!",68 )))69 .await70 .expect("Can not send!");7172 //spawn an async sender to push some more messages into the server73 let mut send_task = tokio::spawn(async move {74 for i in 1..30 {75 // In any websocket error, break loop.76 if sender77 .send(Message::Text(format!("Message number {i}...").into()))78 .await79 .is_err()80 {81 //just as with server, if send fails there is nothing we can do but exit.82 return;83 }8485 tokio::time::sleep(std::time::Duration::from_millis(300)).await;86 }8788 // When we are done we may want our client to close connection cleanly.89 println!("Sending close to {who}...");90 if let Err(e) = sender91 .send(Message::Close(Some(CloseFrame {92 code: CloseCode::Normal,93 reason: Utf8Bytes::from_static("Goodbye"),94 })))95 .await96 {97 println!("Could not send Close due to {e:?}, probably it is ok?");98 };99 });100101 //receiver just prints whatever it gets102 let mut recv_task = tokio::spawn(async move {103 while let Some(Ok(msg)) = receiver.next().await {104 // print message and break if instructed to do so105 if process_message(msg, who).is_break() {106 break;107 }108 }109 });110111 //wait for either task to finish and kill the other task112 tokio::select! {113 _ = (&mut send_task) => {114 recv_task.abort();115 },116 _ = (&mut recv_task) => {117 send_task.abort();118 }119 }120}121122/// Function to handle messages we get (with a slight twist that Frame variant is visible123/// since we are working with the underlying tungstenite library directly without axum here).124fn process_message(msg: Message, who: usize) -> ControlFlow<(), ()> {125 match msg {126 Message::Text(t) => {127 println!(">>> {who} got str: {t:?}");128 }129 Message::Binary(d) => {130 println!(">>> {who} got {} bytes: {d:?}", d.len());131 }132 Message::Close(c) => {133 if let Some(cf) = c {134 println!(135 ">>> {who} got close with code {} and reason `{}`",136 cf.code, cf.reason137 );138 } else {139 println!(">>> {who} somehow got close message without CloseFrame");140 }141 return ControlFlow::Break(());142 }143144 Message::Pong(v) => {145 println!(">>> {who} got pong with {v:?}");146 }147 // Just as with axum server, the underlying tungstenite websocket library148 // will handle Ping for you automagically by replying with Pong and copying the149 // v according to spec. But if you need the contents of the pings you can see them here.150 Message::Ping(v) => {151 println!(">>> {who} got ping with {v:?}");152 }153154 Message::Frame(_) => {155 unreachable!("This is never supposed to happen")156 }157 }158 ControlFlow::Continue(())159}