沈丘营商办后台前端项目
346149741
2024-06-18 9fb6a0ff49c2af567be2e3adaf93c4c301b3f102
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
export default class WebSockBase {
  webSock: WebSocket | null;
 
  public set onOpen(fnc: () => void) {
    this.webSock!.onopen = fnc;
  }
 
  public set onError(fnc: () => void) {
    this.webSock!.onerror = fnc;
  }
 
  public set onMessage(fnc: (value: any) => void) {
    this.webSock!.onmessage = fnc;
  }
 
  public set onClose(fnc: () => void) {
    this.webSock!.onclose = fnc;
  }
 
  constructor() {
    this.webSock = null;
  }
  /**
   * 创建连接
   * @param url
   */
  createdWebSock(url: string) {
    this.webSock = new WebSocket(`ws://${url}`);
    this.webSock.onopen = (ev: Event) => {
      console.log("websock--连接成功");
    };
    this.webSock.onclose = (ev: Event) => {
      console.log("websock--连接关闭");
    };
    this.webSock.onerror = (ev: Event) => {
      console.log("websock--连接失败");
    };
  }
 
  /**
   * 判断连接是否在线
   */
  public isConnect = () => {
    return this.webSock && this.webSock.readyState == WebSocket.OPEN;
  };
 
  /**
   * 关闭连接
   */
  public offConcat = () => {
    return new Promise<void>((resolve, reject) => {
      if (this.webSock) {
        this.webSock.close();
        this.webSock = null;
        resolve();
      } else {
        reject();
      }
    });
  };
}