WebSocket
astrobox:psys-host-v4/websocket,Level 4 新增。
让插件作为客户端连到外部的 ws:// / wss:// 服务器。连接由宿主建立并持有,插件拿到的是一个连接 id;
wss:// 用宿主内置的根证书校验。
用了这个接口的插件需要带有它的宿主版本,旧宿主上加载时会报缺少导入。
权限
不需要。和发 HTTP 请求一样,能连 WebSocket 并不比能发请求多出什么能力。
接口
record connect-options {
url: string, // ws:// 或 wss://
headers: list<header>, // 额外的握手请求头
protocols: list<string>, // 想用的子协议,按优先级排
event-name: option<string>, // 填了按推送方式收消息,留空用 receive 拉取
timeout-ms: option<u32>, // 建立连接的超时,默认 15 秒,最多 120 秒
ping-interval-ms: option<u32>, // 保活 ping 的间隔,最少 5 秒;不填不主动 ping
}
record connection-info {
id: u32,
protocol: option<string>, // 服务器选中的子协议
headers: list<header>, // 握手响应头
}
variant message { text(string), binary(list<u8>) }
variant incoming {
text(string),
binary(list<u8>),
closed(close-info),
}
record close-info {
code: u16, // 对方没给是 1005,异常断开是 1006
reason: string,
error: option<string>, // 异常断开的原因;正常关闭为 none
}
connect: async func(options: connect-options) -> result<connection-info, string>;
send: async func(id: u32, message: message) -> result<_, string>;
receive: async func(id: u32, timeout-ms: option<u64>) -> result<option<incoming>, string>;
close: async func(id: u32, code: option<u16>, reason: option<string>) -> result<_, string>;两种收消息的方式
在 connect 时二选一,之后不能换。
拉取:receive
event-name 留空。用 receive 一条条取,timeout-ms 内没有新消息返回 none,省略表示一直等。
适合「发一条、等回复」的写法:
use crate::astrobox::psys_host_v4::websocket;
let conn = websocket::connect(websocket::ConnectOptions {
url: "wss://example.com/ws".into(),
headers: vec![websocket::Header {
name: "Authorization".into(),
value: format!("Bearer {token}"),
}],
protocols: vec![],
event_name: None,
timeout_ms: None,
ping_interval_ms: Some(20_000),
})
.await?;
websocket::send(conn.id, websocket::Message::Text(r#"{"op":"hello"}"#.into())).await?;
match websocket::receive(conn.id, Some(5_000)).await? {
Some(websocket::Incoming::Text(reply)) => { /* 处理回复 */ }
Some(websocket::Incoming::Binary(data)) => { /* … */ }
Some(websocket::Incoming::Closed(info)) => { /* 对方关了,id 已作废 */ }
None => { /* 5 秒内没回 */ }
}
websocket::close(conn.id, None, None).await?;宿主最多替你攒 16 MiB 没取走的消息,攒满就先不读,数据压在网络那头,不会丢。
JavaScript 插件不要用拉取方式。 JS 里宿主接口是同步调用的,等
receive会让整个插件停在那里, 别的事件都进不来。请用推送。
推送:event-name
填一个事件名。每收到一条,宿主以插件消息送进 on-event(plugin-message):
{ "eventName": "chat.ws", "payload": "{\"id\":1,\"type\":\"text\",\"data\":\"hi\"}", "host": true }里层 payload 是下面三种之一:
type | 其它字段 |
|---|---|
text | id、data(字符串) |
binary | id、data(base64) |
closed | id、code、reason、error(正常关闭为 null) |
同一个连接上,一条处理完(on-event 返回)才送下一条,所以顺序有保证、不会并发处理。
处理得慢宿主就先不读,所以 on-event 里别长时间等待(比如弹窗等用户点)。
宿主发的插件消息都带 "host": true,别的插件用 event.send-event 广播的消息不会有。
处理推送时先检查它,免得被别的插件用同名事件冒充:
import { connect, send } from 'astrobox:psys-host-v4/websocket';
export const lifecycle = {
async onLoad() {
// JS 里宿主接口是同步调用的,不需要 await;失败会抛异常
const conn = connect({
url: 'wss://example.com/ws',
headers: [],
protocols: [],
eventName: 'chat.ws',
timeoutMs: undefined,
pingIntervalMs: 20000,
});
send(conn.id, { tag: 'text', val: JSON.stringify({ op: 'hello' }) });
},
};
export const event = {
async onEvent(eventType, payload) {
if (eventType !== 'plugin-message') return '';
const outer = JSON.parse(payload);
if (outer.host !== true || outer.eventName !== 'chat.ws') return '';
const msg = JSON.parse(outer.payload);
if (msg.type === 'text') {
// 处理 msg.data
} else if (msg.type === 'closed') {
// 对方关了或断了:按需重连
}
return '';
},
// …
};二进制消息量大时,推送要 base64 一遍,用拉取更划算。
连接与关闭
connect握手成功才返回;被拒(比如服务器回 401)时错误里带状态码和响应的前一小段。- 连接被对方关闭或异常断开时,插件会收到一次 closed(推送是
type: "closed",拉取是receive返回closed),之后这个 id 作废。 - 插件自己
close的连接,调用后 id 立即作废,不会再收到消息或 closed;关闭握手由宿主在后台做完(对方 5 秒不回就直接断开)。 - 正等在
receive里的调用,在连接被close时会返回错误,不会一直挂着。 - 已被对方关掉、closed 还没取走的连接也可以
close,用来丢掉它。 - 插件停止或热重载时,宿主会关掉它的全部连接(关闭码 1001)。
close 的关闭码只能用 1000–1003、1007–1013 或 3000–4999(1005、1006 这些是保留给「没收到关闭码」「异常断开」的),默认 1000;reason 最多 123 字节。
保活
对方发来的 ping,宿主总会自动回 pong。
ping-interval-ms 填了的话,宿主每隔这么久发一次 ping;连续两个周期什么都没收到就当连接已断,
按异常断开处理(code 1006,error 为 keepalive timed out)。手机切网络、NAT 映射过期这类情况,
TCP 自己往往要好几分钟才会报错,长连接建议开上。插件正在处理消息、宿主暂停读取的那段时间不计入。
限制
| 项目 | 限制 |
|---|---|
| 同时开着的连接 | 每个插件 16 个(含已被对方关闭、closed 还没取走的) |
| 单条消息 | 收发都是 16 MiB;收到超过上限的消息会按异常断开处理 |
| 拉取缓冲 | 16 MiB |
send | 30 秒写不出去按失败处理 |
| 握手请求头 | 最多 64 个,共 16 KiB;Host、Upgrade、Connection、Sec-WebSocket-* 由宿主负责,不能设,子协议请用 protocols |
| URL | 只支持 ws:// / wss://;不支持在 URL 里带用户名密码,请改用 Authorization 头 |