16 个版本
0.2.0 | 2023 年 3 月 22 日 |
---|---|
0.1.13 | 2022 年 3 月 7 日 |
0.1.8 | 2021 年 6 月 7 日 |
0.1.3 | 2020 年 10 月 23 日 |
0.1.0 | 2020 年 4 月 27 日 |
#120 in WebSocket
每月 30 次下载
45KB
997 行
Thruster-SocketIO
这是一个用于 thruster 的 socket.io 绑定库。它允许开发者在 thruster 的基础上使用 socket.io 层作为 http 服务器。
注意:此库仍在开发中。目前,仅实现了 websockets 作为传输,而轮询则是一个正在进行中的工作。
使用方法
注意:当前,此库仅与基于 hyper 的 thruster 服务器一起使用。
要将中间件连接起来,只需执行以下操作
let mut app = App::<HyperRequest, Ctx, ()>::create(generate_context, ());
...
app.get("/socket.io/*", async_middleware!(Ctx, [io]));
您需要这样的 io 中间件
use thruster_socketio::{handle_io, socketio_handler, socketio_listener, SocketIO};
...
#[socketio_listener]
async fn handle_a_message(socket: SocketIO, value: String) -> Result<(), ()> {
println!("Handling [message]: {}", value);
for room in socket.rooms() {
println!("sending to a room: {}", room);
socket.emit_to(room, "chat message", &value).await;
}
Ok(())
}
#[socketio_listener]
async fn join_room(mut socket: SocketIO, value: String) -> Result<(), ()> {
println!("{} joining \"{}\"", socket.id(), &value);
socket.join(&value).await;
Ok(())
}
#[socketio_handler]
async fn handle<'a>(mut socket: SocketIO) -> Result<SocketIO, ()> {
socket.on("chat message", handle_a_message);
socket.on("join room", join_room);
Ok(socket)
}
#[middleware_fn]
pub async fn io(context: Ctx, _next: MiddlewareNext<Ctx>) -> MiddlewareResult<Ctx> {
handle_io(context, handle).await
}
以上代码中有几个关键部分
io
是围绕处理器的一个中间件包装handle
和#[socketio_handler]
宏代表 thruster 捕获到 socket 时的入口点。这是您应该添加任何 socket 初始化 socket(基于每个连接)以及您可能想要添加到给定 socket 的任何监听器的地方。handle_a_message
、join_room
和#[socketio_listener]
是在从 socket 接收到某些事件时触发的监听器(和一个宏)。这很可能是您的大部分逻辑和处理的所在地。
多服务器
目前,我们支持 redis 作为消息的适配器。此使用的体验相当无缝,只需在初始化逻辑中添加如下块
use thruster_socketio::adapter;
use thruster_socketio::redis_pubsub::{
connect_to_pubsub,
RedisAdapter
};
...
tokio::spawn(async {
let _ = connect_to_pubsub("redis://127.0.0.1/", "socketio-example").await.expect("Could not connect to redis :(");
adapter(RedisAdapter{});
});
依赖关系
~17-27MB
~415K SLoC