Skip to content

Latest commit

 

History

History
68 lines (55 loc) · 3.4 KB

README.md

File metadata and controls

68 lines (55 loc) · 3.4 KB

Blunt

github crates.io docs.rs build status

Highly opinionated way to build asynchronous Websocket servers with Rust

How

The world famous example, echo server

#[tokio::main]
async fn main() -> Result<()> {
    ::blunt::builder()
        .for_path_with_ctor("/echo", |ctx| EchoServer { ctx })
        .build()
        .bind("127.0.0.1:3000".parse().expect("Invalid Socket Addr"))
        .await?;

    Ok(())
    
    // now connect your clients to http://127.0.0.1:3000/echo and say something!
}

#[derive(Debug, Default)]
pub struct EchoServer {
    ctx: AppContext,
}

#[blunt::async_trait]
impl WebSocketHandler for EchoServer {
    async fn on_open(&mut self, session_id: Uuid) {
        self.ctx
            .session(session_id)
            .await
            .and_then(|s| {
                s.send(WebSocketMessage::Text(String::from(
                    "Welcome to Echo server!",
                ))).ok()
            });
    }

    async fn on_message(&mut self, session_id: Uuid, msg: WebSocketMessage) {
        self.ctx
            .session(session_id)
            .await
            .and_then(|s| s.send(msg).ok());
    }

    async fn on_close(&mut self, session_id: Uuid, _msg: WebSocketMessage) {
        info!("connection closed for session id {}", session_id);
    }
}

For more code examples please see the examples folder.

License

Tri-Licensed under either of Apache License, Version 2.0, MIT license or MPL-2.0 license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be tri-licensed as above, without any additional terms or conditions.