From 74299a971912c6e6c7a259556d947998a4d08471 Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Wed, 2 Jun 2021 00:10:34 -0700 Subject: [PATCH] Make minor improvements to chat example. --- examples/chat/src/main.rs | 13 +++++++------ examples/chat/static/index.html | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/examples/chat/src/main.rs b/examples/chat/src/main.rs index 17226e60..724d2c3c 100644 --- a/examples/chat/src/main.rs +++ b/examples/chat/src/main.rs @@ -1,18 +1,17 @@ -//! Implements a chat server using async rocket and SSE. - #[macro_use] extern crate rocket; #[cfg(test)] mod tests; use rocket::{State, Shutdown}; -use rocket::form::Form; use rocket::fs::{relative, FileServer}; +use rocket::form::Form; use rocket::response::stream::{EventStream, Event}; +use rocket::serde::{Serialize, Deserialize}; use rocket::tokio::sync::broadcast::{channel, Sender, error::RecvError}; use rocket::tokio::select; -use rocket::serde::{Serialize, Deserialize}; -#[derive(Debug, PartialEq, Clone, FromForm, Deserialize, Serialize, UriDisplayQuery)] +#[derive(Debug, Clone, FromForm, Serialize, Deserialize)] +#[cfg_attr(test, derive(PartialEq, UriDisplayQuery))] #[serde(crate = "rocket::serde")] struct Message { #[field(validate = len(..30))] @@ -22,9 +21,10 @@ struct Message { pub message: String, } +/// Returns an infinite stream of server-sent events. Each event is a message +/// pulled from a broadcast queue sent by the `post` handler. #[get("/events")] async fn events(queue: &State>, mut end: Shutdown) -> EventStream![] { - // Subscribe to messages and map it to an SSE stream let mut rx = queue.subscribe(); EventStream! { loop { @@ -42,6 +42,7 @@ async fn events(queue: &State>, mut end: Shutdown) -> EventStrea } } +/// Receive a message from a form submission and broadcast it to any receivers. #[post("/message", data = "
")] fn post(form: Form, queue: &State>) { // A send 'fails' if there are no active subscribers. That's okay. diff --git a/examples/chat/static/index.html b/examples/chat/static/index.html index d0a556e0..44eacf4b 100644 --- a/examples/chat/static/index.html +++ b/examples/chat/static/index.html @@ -20,7 +20,7 @@ + placeholder="new room..." maxlength="29"> @@ -37,7 +37,7 @@
-