Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-1106· OpenAIHugging Face Arena Human Preference 55K

rocket-ws example that broadcasts one clients messages to all

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Metallama-2-70b-chat’s answer.
  1. User

    rocket-ws example that broadcasts one clients messages to all

  2. 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 /message that accepts POST requests with JSON data representing a message. When a message is received, it is broadcast to all connected clients using the broadcast::Sender stored in the SharedData state.

    We also define a /stream endpoint that returns a broadcast::Receiver to 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.