actix_web_socket_io/
socketio.rs

1use actix::Message;
2use num_enum::{IntoPrimitive, TryFromPrimitive};
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6/// 协议文档 https://github.com/socketio/socket.io-protocol/tree/main?tab=readme-ov-file#exchange-protocol
7#[derive(IntoPrimitive, Clone, Eq, PartialEq, TryFromPrimitive)]
8#[repr(u8)]
9pub enum SocketIOPacketType {
10    // 用于连接
11    Connect = 0,
12    // 用于断开连接
13    Disconnect = 1,
14    // 用于向对方发送数据
15    Event = 2,
16    // 用于数据确认
17    Ack = 3,
18    // 用于连接错误,如鉴权失败
19    ConnectError = 4,
20    // 用于二进制数据
21    BinaryEvent = 5,
22    // 用于二进制数据应答
23    BinaryAck = 6,
24}
25
26/// 协议文档 https://github.com/socketio/engine.io-protocol/tree/main?tab=readme-ov-file#protocol
27#[derive(IntoPrimitive, Clone, Eq, PartialEq, TryFromPrimitive)]
28#[repr(u8)]
29pub enum EngineIOPacketType {
30    // 握手
31    Open = 0,
32    // 传输可以关闭
33    Close = 1,
34    // 心跳
35    Ping = 2,
36    // 心跳
37    Pong = 3,
38    // 发送有效载荷
39    Message = 4,
40    // 升级
41    Upgrade = 5,
42    // 升级
43    Noop = 6,
44}
45
46/// 握手数据 https://github.com/socketio/engine.io-protocol/tree/main?tab=readme-ov-file#handshake
47#[derive(Message, Serialize)]
48#[rtype(result = "Result<(), &'static str>")]
49#[serde(rename_all = "camelCase")]
50pub struct OpenPacket {
51    // 会话 ID
52    pub sid: String,
53    // 可以升级的 transport 列表,默认为 [websocket]
54    pub upgrades: Vec<String>,
55    // 心跳间隔(毫秒), 25000
56    pub ping_interval: u64,
57    // 心跳超时(毫秒), 20000
58    pub ping_timeout: u64,
59    // 每个块的最大字节数, 1000000
60    pub max_payload: usize,
61}
62
63#[derive(Deserialize, Debug)]
64pub struct EventData(pub String, pub Value);
65
66pub enum MessageType {
67    None,
68    // 事件
69    Event(EventData),
70}