#websocket-server #hydra #框架 #应用 #异步 #进程 #容错

hydra-websockets

Hydra框架的WebSocket服务器

26个版本

0.1.30 2024年6月30日
0.1.29 2024年6月27日
0.1.22 2024年5月31日

266异步

Download history 220/week @ 2024-05-20 1345/week @ 2024-05-27 310/week @ 2024-06-03 115/week @ 2024-06-10 133/week @ 2024-06-17 508/week @ 2024-06-24 227/week @ 2024-07-01 18/week @ 2024-07-08 21/week @ 2024-07-15 167/week @ 2024-07-29

每月下载量 190

MIT 许可

290KB
6.5K SLoC

Hydra Websockets

Hydra框架的WebSocket服务器库。

Crates.io Docs.rs MIT licensed Build Status

示例

使用Hydra的基本回显WebSocket服务器。

确保您已将Hydra、Hydra Websockets添加到您的Cargo.toml中

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

然后在您的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)
}

更多示例请查看 examples 文件夹。您可以用以下命令运行它们: cargo run --example=server.

变更日志

查看变更日志

许可

本项目采用MIT许可

贡献

除非您明确声明,否则您提交给Hydra的任何有意贡献均应按照MIT许可进行,不附加任何额外条款或条件。

依赖项

~8–20MB
~270K SLoC