PogWebsocket.ts 2.3 KB

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