PogWebsocket.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import UserM from "../api/UserM";
  2. export interface PogWebsocketListener {
  3. OnMessage(data: any): void;
  4. }
  5. export class PogWebsocket {
  6. clearReconnectTimes() {
  7. this._reconnectTimes = 0;
  8. }
  9. public static create(url: string, message: PogWebsocketListener) {
  10. let pogWebsocket = new PogWebsocket();
  11. pogWebsocket.init(url, message);
  12. return pogWebsocket;
  13. }
  14. public get connected(): boolean {
  15. return this._connected;
  16. }
  17. ping() {
  18. if (!this._connected) {
  19. return;
  20. }
  21. if (!UserM.ins.isLogin()) {
  22. return;
  23. }
  24. let pingData = "ping";
  25. this._ws.send(pingData);
  26. }
  27. // private _url: string;
  28. private _ws: WebSocket;
  29. private _connected: boolean = false;
  30. private _message: PogWebsocketListener;
  31. private _url: string;
  32. private init(url: string, message: PogWebsocketListener) {
  33. this._url = url;
  34. this._message = message;
  35. this._ws = new WebSocket(url);
  36. this._ws.onopen = null;
  37. this._ws.onmessage = null;
  38. this._ws.onclose = null;
  39. this._ws.onerror = null;
  40. this._ws.onopen = this.onOpen.bind(this);
  41. this._ws.onmessage = this.onMessage.bind(this);
  42. this._ws.onclose = this.onClose.bind(this);
  43. this._ws.onerror = this.onError.bind(this);
  44. }
  45. private onOpen() {
  46. console.log("onOpen");
  47. this._connected = true;
  48. this._reconnectTimes = 0;
  49. // this._ws.send(
  50. // JSON.stringify({
  51. // type: "test",
  52. // data: "test",
  53. // })
  54. // );
  55. }
  56. private onMessage(data: MessageEvent) {
  57. if (data.data == "pong") {
  58. return;
  59. }
  60. this._message.OnMessage(data);
  61. }
  62. private _reconnectTimes: number = 0;
  63. private onClose(event: CloseEvent) {
  64. console.log("onClose", event);
  65. this._connected = false;
  66. this.reconnect();
  67. }
  68. reconnect() {
  69. this._reconnectTimes++;
  70. if (this._reconnectTimes >= 3) {
  71. return;
  72. }
  73. console.warn("reconnect", this._reconnectTimes);
  74. // if (this._ws.readyState == WebSocket.CONNECTING) {
  75. // return;
  76. // }
  77. let self = this;
  78. setTimeout(() => {
  79. self.init(self._url, self._message);
  80. }, 2000 * self._reconnectTimes);
  81. }
  82. private onError(event: Event) {
  83. console.log("onError", event);
  84. this._connected = false;
  85. this._reconnectTimes = 0;
  86. this.reconnect();
  87. }
  88. public async send(data: any) {
  89. if (!this._connected) {
  90. return;
  91. }
  92. await this._ws.send(data);
  93. }
  94. public close() {
  95. this._ws.close();
  96. }
  97. }