HyperlaneWebSocket插件
2025年5月31日大约 1 分钟hyperlane-plugin-websocket
hyperlane 框架的 WebSocket 插件
安装
使用以下命令添加此依赖:
cargo add hyperlane-plugin-websocket
使用示例
use hyperlane::*;
use hyperlane_plugin_websocket::*;
use hyperlane_utils::*;
static BROADCAST_MAP: OnceLock<WebSocket> = OnceLock::new();
fn get_broadcast_map() -> &'static WebSocket {
BROADCAST_MAP.get_or_init(|| WebSocket::new())
}
async fn callback(ws_ctx: Context) {
let body: RequestBody = ws_ctx.get_request_body().await;
ws_ctx.set_response_body(body).await;
}
async fn send_callback(_: Context) {}
async fn private_chat(ctx: Context) {
let my_name: String = ctx.get_route_param("my_name").await.unwrap();
let your_name: String = ctx.get_route_param("your_name").await.unwrap();
get_broadcast_map()
.run(
&ctx,
DEFAULT_BUFFER_SIZE,
BroadcastType::PointToPoint(&my_name, &your_name),
callback,
send_callback,
)
.await;
}
async fn group_chat(ctx: Context) {
let your_name: String = ctx.get_route_param("group_name").await.unwrap();
get_broadcast_map()
.run(
&ctx,
DEFAULT_BUFFER_SIZE,
BroadcastType::PointToGroup(&your_name),
callback,
send_callback,
)
.await;
}
#[tokio::main]
async fn main() {
let server: Server = Server::new();
server.host("0.0.0.0").await;
server.port(60000).await;
server.enable_nodelay().await;
server.disable_linger().await;
server.http_line_buffer_size(4096).await;
server.websocket_buffer_size(4096).await;
server.disable_inner_websocket_handle("/:group_name").await;
server.route("/:group_name", group_chat).await;
server
.disable_inner_websocket_handle("/:my_name/:your_name")
.await;
server.route("/:my_name/:your_name", private_chat).await;
server.run().await.unwrap();
}
许可证
本项目使用 MIT 协议,详情请参见 LICENSE 文件。
贡献
欢迎贡献代码!请提交 issue 或 pull request。
联系方式
如有任何问题,请联系作者 [email protected]。