26 releases

0.1.30 Jun 30, 2024
0.1.29 Jun 27, 2024
0.1.22 May 31, 2024

#217 in Asynchronous

Download history 1044/week @ 2024-05-23 754/week @ 2024-05-30 161/week @ 2024-06-06 140/week @ 2024-06-13 202/week @ 2024-06-20 402/week @ 2024-06-27

1,083 downloads per month

MIT license

290KB
6.5K SLoC

Hydra Websockets

A websocket server library for the hydra framework.

Crates.io Docs.rs MIT licensed Build Status

Example

A basic echo websocket server with Hydra.

Make sure you have added Hydra, Hydra Websockets in your Cargo.toml:

[dependencies]
hydra = "0.1"
hydra-websockets = "0.1"

Then, in your main.rs:

use std::net::SocketAddr;

use hydra::Application;
use hydra::ExitReason;
use hydra::GenServer;
use hydra::GenServerOptions;
use hydra::Pid;
use hydra::Process;

use hydra_websockets::WebsocketCommands;
use hydra_websockets::WebsocketHandler;
use hydra_websockets::WebsocketMessage;
use hydra_websockets::WebsocketRequest;
use hydra_websockets::WebsocketResponse;
use hydra_websockets::WebsocketServer;
use hydra_websockets::WebsocketServerConfig;

struct MyWebsocketHandler;

impl WebsocketHandler for MyWebsocketHandler {
    type Message = ();

    fn accept(
        _request: &WebsocketRequest,
        response: WebsocketResponse,
    ) -> Result<(WebsocketResponse, Self), ExitReason> {
        // You can extract any header information from `request` and pass it to the handler.
        Ok((response, MyWebsocketHandler))
    }

    async fn websocket_handle(
        &mut self,
        message: WebsocketMessage,
    ) -> Result<Option<WebsocketCommands>, ExitReason> {
        match message {
            WebsocketMessage::Text(text) => {
                tracing::info!(handler = ?Process::current(), message = ?text, "Got message");

                // Echo the command back to the client.
                Ok(Some(WebsocketCommands::with_send(text)))
            }
            _ => {
                // Hydra websockets automatically responds to ping requests.
                Ok(None)
            }
        }
    }
}

struct MyWebsocketApplication;

impl Application for MyWebsocketApplication {
    async fn start(&self) -> Result<Pid, ExitReason> {
        let address: SocketAddr = "127.0.0.1:1337".parse().unwrap();
        let config = WebsocketServerConfig::new(address);

        WebsocketServer::<MyWebsocketHandler>::new(config)
            .start_link(GenServerOptions::new())
            .await
    }
}

fn main() {
    Application::run(MyWebsocketApplication)
}

Find more examples in the examples folder. You can run them with: cargo run --example=server.

Changelog

View Changelog

License

This project is licensed under the MIT license

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Hydra by you, shall be licensed as MIT, without any additional terms or conditions.

Dependencies

~8–20MB
~268K SLoC