mirror of https://github.com/rwf2/Rocket.git
Make minor improvements to chat example.
This commit is contained in:
parent
f1ecb79a7e
commit
74299a9719
|
@ -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<Sender<Message>>, 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<Sender<Message>>, mut end: Shutdown) -> EventStrea
|
|||
}
|
||||
}
|
||||
|
||||
/// Receive a message from a form submission and broadcast it to any receivers.
|
||||
#[post("/message", data = "<form>")]
|
||||
fn post(form: Form<Message>, queue: &State<Sender<Message>>) {
|
||||
// A send 'fails' if there are no active subscribers. That's okay.
|
||||
|
|
|
@ -20,7 +20,7 @@
|
|||
|
||||
<form id="new-room">
|
||||
<input type="text" name="name" id="name" autocomplete="off"
|
||||
placeholder="new room..." maxlength="30"></input>
|
||||
placeholder="new room..." maxlength="29"></input>
|
||||
<button type="submit">+</button>
|
||||
</form>
|
||||
</div>
|
||||
|
@ -37,7 +37,7 @@
|
|||
</div>
|
||||
|
||||
<form id="new-message">
|
||||
<input type="text" name="username" id="username" maxlength="20"
|
||||
<input type="text" name="username" id="username" maxlength="19"
|
||||
placeholder="guest" autocomplete="off">
|
||||
<input type="text" name="message" id="message" autocomplete="off"
|
||||
placeholder="Send a message..." autofocus>
|
||||
|
|
Loading…
Reference in New Issue