Files
JoyD/Windows/Rust/CubeLib/README.md
2026-04-07 13:55:40 +08:00

108 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# CubeLib - Rust WebSocket Library
Rust 版本的 CubeLib提供 WebSocket 通信功能。
## 结构
```
CubeLib/
├── Cargo.toml
├── src/
│ ├── lib.rs # 库入口
│ └── websocket/
│ ├── mod.rs # 模块定义
│ ├── client.rs # WebSocket 客户端
│ ├── config.rs # 配置类
│ ├── message.rs # 消息类型
│ └── error.rs # 错误类型
└── README.md
```
## 功能特性
- **事件驱动**:支持 Connected、Disconnected、Message、Error 等回调
- **自动重连**:支持指数退避的重连机制
- **自定义头**:支持设置 ClientType 等 HTTP 头
- **心跳保活**:可配置的心跳间隔
- **消息队列**:离线时自动缓存消息,连接后自动发送
- **调试模式**:可选的日志输出
## 快速开始
```rust
use cube_lib::websocket::{WebSocketClient, WebSocketConfig};
#[tokio::main]
async fn main() {
let config = WebSocketConfig::new("ws://localhost:8087/ws")
.with_client_type("Updater")
.with_debug(true);
let mut client = WebSocketClient::new(config);
// 设置事件回调
client.on_connected(|url| {
println!("Connected to: {}", url);
});
client.on_message(|msg_type, data| {
println!("Received [{}]: {:?}", msg_type, data);
});
client.on_disconnected(|| {
println!("Disconnected");
});
// 连接
client.connect().await;
// 发送消息(格式与 MasterSuite 后端兼容)
client.send("ping", serde_json::json!({
"timestamp": "2024-01-01 00:00:00"
})).await;
// 保持运行
tokio::signal::ctrl_c().await.ok();
client.disconnect().await;
}
```
## WebSocketConfig 配置项
| 字段 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `ws_url` | String | `ws://localhost:8087/ws` | 服务器地址 |
| `auto_connect` | bool | `true` | 初始化时自动连接 |
| `reconnect` | bool | `true` | 断开时自动重连 |
| `max_reconnect_delay_ms` | u64 | `30000` | 最大重连延迟(毫秒) |
| `reconnect_delay_ms` | u64 | `1000` | 初始重连延迟(毫秒) |
| `debug_mode` | bool | `false` | 调试模式 |
| `heartbeat_interval_ms` | u64 | `30000` | 心跳间隔(毫秒)0=禁用 |
| `connect_timeout_ms` | u64 | `10000` | 连接超时(毫秒) |
| `max_queue_size` | usize | `100` | 消息队列最大长度 |
| `client_type` | Option\<String\> | `None` | 客户端类型标识 |
| `custom_headers` | Vec\<(String, String)\> | `[]` | 自定义 HTTP 头 |
## 消息格式
与 MasterSuite 后端兼容的 JSON 格式:
```json
{
"Type": "message_type",
"Data": { ... },
"MessageId": "optional_id"
}
```
## 集成到项目
`Cargo.toml` 中添加:
```toml
[dependencies]
cube_lib = { path = "../Rust/CubeLib" }
```
或从 Git 引用(待发布后)。