Home > SYS_WebSocket > register
SYS_WebSocket.register() method
Register a WebSocket connection
Signature
function register(
id: string,
serviceUri: string,
receiveMessageCallFn?: (event: MessageEvent<any>) => void | Promise<void>,
connectedCallFn?: () => void | Promise<void>,
protocols?: string | Array<string>,
): void;2
3
4
5
6
7
Parameters
Parameter | Type | Description |
|---|---|---|
id | string | Custom WebSocket ID |
serviceUri | string | WebSocket service URI |
receiveMessageCallFn | (event: MessageEvent<any>) => void | Promise<void> | (Optional) Callback function when a message is received |
connectedCallFn | () => void | Promise<void> | (Optional) Callback function when the connection is established |
protocols | string | Array<string> | (Optional) Sub-protocols |
Returns
void
Remarks
It can be used to detect whether the WebSocket connection is normal before execution, but note that **do not attempt connections with the same ID but different parameters**, as this will cause confusion: if a WebSocket connection with the specified ID is active, changes to other parameters will not be applied
Note: This API requires the user to enable the extension external interaction permission, if not enabled, it will always throw Error
Example
// 1. 注册连接,挂上「连接成功」与「收到消息」两个回调
eda.sys_WebSocket.register('嘉立创示例_注册', 'ws://127.0.0.1:49620', (event) => {
// 服务器推送的每条消息都会进入这个回调(event.data 是消息内容)
console.log('收到服务器消息:', event.data);
}, () => {
console.log('连接已建立');
});
// 2. register 是同步调用,只登记意图,握手需要一点时间,等待回调触发
await new Promise(r => setTimeout(r, 1500));
// 3. 演示完毕后关闭连接,避免残留
eda.sys_WebSocket.close('嘉立创示例_注册');
console.log('已关闭连接');2
3
4
5
6
7
8
9
10
11
12
13
14