/**Wxweb scoket 客户端*/ export class WXWsClient { public onConnected(): void { }; public onError(err: string): void { }; public onClosing(): void { }; public onClosed(code: number, reason: string): void { }; public onMessage(msg: string | ArrayBuffer): void { }; // private _ws: any | null = null; /** WebSocket对象*/get ws() { return this._ws }; /** 连接地址*/ private _url: string | null = null; /**证书*/ private _ca?: string; constructor(url: string, ca?: string, autoConnect?: boolean) { this._ca = ca; this._url = url; if (autoConnect) this.connect(); } /** * 获取当前连接状态 * @returns 是否处于活动状态 */ get isActive(): boolean { return this._ws != null; } /** *是否正在关闭 */ private get isClosing(): boolean { return this._closing; } /**是否已经关闭 */ private get isClosed(): boolean { return this._ws === null; } /**手动连接*/ connect() { if (this.isActive) return false; const url = this._url; if (!url) return false; try { this.close(); //eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore //eslint-disable-next-line @typescript-eslint/no-unsafe-call const ws = wx.connectSocket({ url: url, header: { 'content-type': 'application/json' } }) ws.onClose((res) => { this._ws = null; this.onClosed(res.code, res.reason); }); ws.onError((res) => { this.onError(res.errMsg); }); ws.onMessage((res) => { this.onMessage(res.data); }) ws.onOpen((res) => { console.log(res.header); console.log(res.profile); this.onConnected(); }) this._ws = ws; } catch (error) { this.onError(error instanceof Error ? error.message : 'Unknown error'); } return true; } private _closing: boolean = false; /** * 主动关闭WebSocket连接 */ close(code?: number, reason?: string): void { if (this.isClosed || this.isClosing) return; this._closing = true; this.onClosing(); this._ws.close({ code: code, reason: reason, success: (res) => { // 关闭成功的回调 chsdk.log.log("close success", res); }, fail: (res) => { // 关闭失败的回调 chsdk.log.log("close fail", res); }, }); } /** * 发送数据 * @param data 指定格式数据 */ send(data: string | ArrayBuffer): void { this._ws.send({ data: data, success: (ret) => { console.log('成功', ret) }, fail: (ret) => { console.log('失败', ret) }, complete: (ret) => { console.log('完成', ret) }, }) } }