webSocketConnection.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. const cleanPeriod = 60*1000;//1 минута
  2. class WebSocketConnection {
  3. //messageLifeTime в минутах (cleanPeriod)
  4. constructor(messageLifeTime = 5) {
  5. this.ws = null;
  6. this.timer = null;
  7. this.listeners = [];
  8. this.messageQueue = [];
  9. this.messageLifeTime = messageLifeTime;
  10. this.requestId = 0;
  11. }
  12. addListener(listener) {
  13. if (this.listeners.indexOf(listener) < 0)
  14. this.listeners.push(Object.assign({regTime: Date.now()}, listener));
  15. }
  16. //рассылаем сообщение и удаляем те обработчики, которые его получили
  17. emit(mes, isError) {
  18. const len = this.listeners.length;
  19. if (len > 0) {
  20. let newListeners = [];
  21. for (const listener of this.listeners) {
  22. let emitted = false;
  23. if (isError) {
  24. if (listener.onError)
  25. listener.onError(mes);
  26. emitted = true;
  27. } else {
  28. if (listener.onMessage) {
  29. if (listener.requestId) {
  30. if (listener.requestId === mes.requestId) {
  31. listener.onMessage(mes);
  32. emitted = true;
  33. }
  34. } else {
  35. listener.onMessage(mes);
  36. emitted = true;
  37. }
  38. } else {
  39. emitted = true;
  40. }
  41. }
  42. if (!emitted)
  43. newListeners.push(listener);
  44. }
  45. this.listeners = newListeners;
  46. }
  47. return this.listeners.length != len;
  48. }
  49. open(url) {
  50. return new Promise((resolve, reject) => {
  51. if (this.ws && this.ws.readyState == WebSocket.OPEN) {
  52. resolve(this.ws);
  53. } else {
  54. let protocol = 'ws:';
  55. if (window.location.protocol == 'https:') {
  56. protocol = 'wss:'
  57. }
  58. url = url || `${protocol}//${window.location.host}/ws`;
  59. this.ws = new WebSocket(url);
  60. if (this.timer) {
  61. clearTimeout(this.timer);
  62. }
  63. this.timer = setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  64. let resolved = false;
  65. this.ws.onopen = (e) => {
  66. resolved = true;
  67. resolve(e);
  68. };
  69. this.ws.onmessage = (e) => {
  70. try {
  71. const mes = JSON.parse(e.data);
  72. this.messageQueue.push({regTime: Date.now(), mes});
  73. let newMessageQueue = [];
  74. for (const message of this.messageQueue) {
  75. if (!this.emit(message.mes)) {
  76. newMessageQueue.push(message);
  77. }
  78. }
  79. this.messageQueue = newMessageQueue;
  80. } catch (e) {
  81. this.emit(e.message, true);
  82. }
  83. };
  84. this.ws.onerror = (e) => {
  85. this.emit(e.message, true);
  86. if (!resolved)
  87. reject(e);
  88. };
  89. }
  90. });
  91. }
  92. //timeout в минутах (cleanPeriod)
  93. message(requestId, timeout = 2) {
  94. return new Promise((resolve, reject) => {
  95. this.addListener({
  96. requestId,
  97. timeout,
  98. onMessage: (mes) => {
  99. if (mes.error) {
  100. reject(mes.error);
  101. } else {
  102. resolve(mes);
  103. }
  104. },
  105. onError: (e) => {
  106. reject(e);
  107. }
  108. });
  109. });
  110. }
  111. send(req) {
  112. if (this.ws && this.ws.readyState == WebSocket.OPEN) {
  113. const requestId = ++this.requestId;
  114. this.ws.send(JSON.stringify(Object.assign({requestId}, req)));
  115. return requestId;
  116. } else {
  117. throw new Error('WebSocket connection is not ready');
  118. }
  119. }
  120. close() {
  121. if (this.ws && this.ws.readyState == WebSocket.OPEN) {
  122. this.ws.close();
  123. }
  124. }
  125. periodicClean() {
  126. try {
  127. this.timer = null;
  128. const now = Date.now();
  129. //чистка listeners
  130. let newListeners = [];
  131. for (const listener of this.listeners) {
  132. if (now - listener.regTime < listener.timeout*cleanPeriod - 50) {
  133. newListeners.push(listener);
  134. } else {
  135. if (listener.onError)
  136. listener.onError('Время ожидания ответа истекло');
  137. }
  138. }
  139. this.listeners = newListeners;
  140. //чистка messageQueue
  141. let newMessageQueue = [];
  142. for (const message of this.messageQueue) {
  143. if (now - message.regTime < this.messageLifeTime*cleanPeriod - 50) {
  144. newMessageQueue.push(message);
  145. }
  146. }
  147. this.messageQueue = newMessageQueue;
  148. } finally {
  149. if (this.ws.readyState == WebSocket.OPEN) {
  150. this.timer = setTimeout(() => { this.periodicClean(); }, cleanPeriod);
  151. }
  152. }
  153. }
  154. }
  155. export default new WebSocketConnection();