123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- /**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);
- }
- }
|