rocket-ws example that broadcasts one clients messages to all
- User
rocket-ws example that broadcasts one clients messages to all
- Assistant
Sure! Here's an example of a simple Rocket WebSocket server that broadcasts one client's messages to all connected clients:
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; use rocket_contrib::json::Json; use rocket::State; use rocket::http::Status; use rocket::serde::json::serde_json::{Value, json}; use rocket::serde::Deserialize; use rocket::tokio::sync::broadcast; use std::sync::{Arc, Mutex}; #[derive(Deserialize)] struct Message { text: String, } #[derive(Clone)] struct SharedData { sender: broadcast::Sender<Value>, } #[post("/message", data = "<message>")] fn post_message(message: Json<Message>, shared_data: State<Arc<Mutex<SharedData>>>) -> Status { let message = message.into_inner(); let json = json!({ "text": message.text }); shared_data.lock().unwrap().sender.send(json).unwrap(); Status::Accepted } #[get("/stream")] async fn stream(shared_data: State<Arc<Mutex<SharedData>>>) -> broadcast::Receiver<Value> { shared_data.lock().unwrap().sender.subscribe() } #[launch] fn rocket() -> _ { let (sender, _) = broadcast::channel(10); rocket::build() .manage(Arc::new(Mutex::new(SharedData { sender }))) .mount("/", routes![post_message, stream]) }In this example, we define a Rocket endpoint
/messagethat accepts POST requests with JSON data representing a message. When a message is received, it is broadcast to all connected clients using thebroadcast::Senderstored in theSharedDatastate.We also define a
/streamendpoint that returns abroadcast::Receiverto the client, allowing it to receive messages as they are broadcasted.This example demonstrates a simple WebSocket server using Rocket that broadcasts messages from one client to all connected clients.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.