|
| 1 | +use std::{pin::Pin, time::Duration}; |
| 2 | + |
| 3 | +use rust_socketio::{ |
| 4 | + asynchronous::{Client, ClientBuilder}, |
| 5 | + Payload, |
| 6 | +}; |
| 7 | + |
| 8 | +const PING_INTERVAL: Duration = Duration::from_millis(1000); |
| 9 | +const POLLING_PERCENTAGE: f32 = 0.05; |
| 10 | +const MAX_CLIENT: usize = 200; |
| 11 | + |
| 12 | +fn cb(_: Payload, socket: Client) -> Pin<Box<dyn std::future::Future<Output = ()> + Send>> { |
| 13 | + Box::pin(async move { |
| 14 | + tokio::spawn(async move { |
| 15 | + let mut inter = tokio::time::interval(PING_INTERVAL); |
| 16 | + loop { |
| 17 | + inter.tick().await; |
| 18 | + let _ = socket.emit("ping", serde_json::Value::Null).await; |
| 19 | + let _ = socket |
| 20 | + .emit("ping", (0..u8::MAX).into_iter().collect::<Vec<u8>>()) |
| 21 | + .await; |
| 22 | + } |
| 23 | + }); |
| 24 | + }) |
| 25 | +} |
| 26 | +#[tokio::main] |
| 27 | +async fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 28 | + tokio::spawn(async move { |
| 29 | + for _ in 0..MAX_CLIENT { |
| 30 | + let random: f32 = rand::random(); |
| 31 | + let transport_type = if POLLING_PERCENTAGE > random { |
| 32 | + rust_socketio::TransportType::Polling |
| 33 | + } else { |
| 34 | + rust_socketio::TransportType::WebsocketUpgrade |
| 35 | + }; |
| 36 | + // get a socket that is connected to the admin namespace |
| 37 | + ClientBuilder::new("http://localhost:3000/") |
| 38 | + .transport_type(transport_type) |
| 39 | + .namespace("/") |
| 40 | + .on("open", cb) |
| 41 | + .on("error", |err, _| { |
| 42 | + Box::pin(async move { eprintln!("Error: {:#?}", err) }) |
| 43 | + }) |
| 44 | + .connect() |
| 45 | + .await |
| 46 | + .expect("Connection failed"); |
| 47 | + } |
| 48 | + }); |
| 49 | + tokio::time::sleep(Duration::from_secs(60)).await; |
| 50 | + |
| 51 | + Ok(()) |
| 52 | +} |
0 commit comments