-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathwebsocket.mbt
More file actions
80 lines (70 loc) · 1.76 KB
/
websocket.mbt
File metadata and controls
80 lines (70 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
///|
pub(all) struct WebSocketPeer {
connection_id : String
mut subscribed_channels : Array[String]
}
///|
pub fn WebSocketPeer::text(self : WebSocketPeer, message : String) -> Unit {
// 真正发送到后端连接
ws_send(self.connection_id, message)
}
///|
pub fn WebSocketPeer::binary(self : WebSocketPeer, message : Bytes) -> Unit {
// 真正发送到后端连接
ws_send_bytes(self.connection_id, message)
}
///|
pub fn WebSocketPeer::pong(self : WebSocketPeer) -> Unit {
// 真正发送到后端连接
ws_pong(self.connection_id)
}
///|
pub fn WebSocketPeer::subscribe(self : WebSocketPeer, channel : String) -> Unit {
if !self.subscribed_channels.contains(channel) {
self.subscribed_channels.push(channel)
ws_subscribe(self.connection_id, channel)
}
}
///|
pub fn WebSocketPeer::unsubscribe(
self : WebSocketPeer,
channel : String,
) -> Unit {
let mut index = None
for i = 0; i < self.subscribed_channels.length(); i = i + 1 {
if self.subscribed_channels[i] == channel {
index = Some(i)
break
}
}
match index {
Some(i) => {
ignore(self.subscribed_channels.remove(i))
ws_unsubscribe(self.connection_id, channel)
}
None => ()
}
}
///|
pub fn WebSocketPeer::publish(channel : String, message : String) -> Unit {
ws_publish(channel, message)
}
///|
pub fn WebSocketPeer::to_string(self : WebSocketPeer) -> String {
"WebSocketPeer(\{self.connection_id})"
}
///|
pub enum WebSocketEvent {
Open(WebSocketPeer)
Message(WebSocketPeer, WebSocketAggregatedMessage)
Close(WebSocketPeer)
}
///|
pub enum WebSocketAggregatedMessage {
Text(String)
Binary(Bytes)
Ping
}
///|
// WebSocket 路由的事件处理器类型(不返回 HttpBody)
pub type WebSocketHandler = (WebSocketEvent) -> Unit