/**web scoket 客户端*/ export class WsClient { public onConnected(evt: any): void { }; public onError(err: any): void { }; public onClosing(): void { }; public onClosed(event: CloseEvent): void { }; public onMessage(msg: MessageEvent): void { }; // private _ws: WebSocket | 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(); } /**连接成功时的回调 */ private _onConnected(evt: any) { this.onConnected(evt); } /**收到消息时的回调 */ private _onMessage(msg: MessageEvent) { this.onMessage(msg); } /** 错误处理回调 */ private _onError(err: any) { this.onError(err); } /**连接关闭时的回调 */ private _onClosed(event: CloseEvent) { this.onClosed(event); } /** * 获取当前连接状态 * @returns 是否处于活动状态 */ get isActive(): boolean { return this._ws?.readyState === WebSocket.OPEN; } /** * 检查是否正在连接 * @returns 是否正在连接 */ private get isConnecting(): boolean { return this._ws?.readyState === WebSocket.CONNECTING; } /** *是否正在关闭 */ private get isClosing(): boolean { return this._ws?.readyState === WebSocket.CLOSING; } /**是否已经关闭 */ private get isClosed(): boolean { return this._ws?.readyState === WebSocket.CLOSED; } /**手动连接*/ connect() { if (this.isConnecting) return false; if (this.isActive) return false; const url = this._url; if (!url) return false; try { //eslint-disable-next-line @typescript-eslint/ban-ts-comment //@ts-ignore //eslint-disable-next-line @typescript-eslint/no-unsafe-call const ws = this._ca && url.startsWith('wss://') ? new WebSocket(url, {}, this._ca) : new WebSocket(url) ws.binaryType = 'arraybuffer'; ws.onmessage = this._onMessage.bind(this); ws.onopen = this._onConnected.bind(this); ws.onerror = this._onError.bind(this); ws.onclose = this._onClosed.bind(this); this._ws = ws; } catch (error) { this._onError(error instanceof Error ? error.message : 'Unknown error'); } return true; } /** * 主动关闭WebSocket连接 */ close(code?: number, reason?: string): void { if (this.isClosed || this.isClosing) return; this.onClosing(); this._ws.close(code, reason); } /** * 发送数据 * @param data 指定格式数据 */ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void { this._ws.send(data); } }