| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- /**tt scoket 客户端*/
- export class TTWsClient {
- 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 = tt.connectSocket({
- url: url,
- success: (res) => {
- chsdk.log.info("WebSocket创建成功", res);
- },
- fail: (res) => {
- chsdk.log.info("WebSocket创建失败", res);
- },
- });
- ws.onOpen(() => {
- chsdk.log.info("WebSocket 已连接");
- this.onConnected();
- });
- ws.onClose((res) => {
- this._ws = null;
- this.onClosed(res?.code, res?.reason);
- chsdk.log.info("WebSocket 已断开");
- });
- ws.onError((error) => {
- chsdk.log.info("WebSocket 发生错误:", error);
- this.onError(error);
- });
- ws.onMessage((message) => {
- chsdk.log.info("socket message:", message);
- this.onMessage(message.data);
- });
- 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.info("close success", res);
- },
- fail: (res) => {
- // 关闭失败的回调
- chsdk.log.info("close fail", res);
- },
- });
- }
- /**
- * 发送数据
- * @param data 指定格式数据
- */
- send(data: string | ArrayBuffer): void {
- this._ws.send({
- data: data,
- success: (ret) => { chsdk.log.info('成功', ret) },
- fail: (ret) => { chsdk.log.info('失败', ret) },
- complete: (ret) => { chsdk.log.info('完成', ret) },
- })
- }
- }
|