Shopping List v2.0
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ws.js 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. export default class WSockMan {
  2. constructor(url) {
  3. this.ready = false;
  4. this.sock = null;
  5. this.url = url;
  6. this.sendQ = [];
  7. this.ackQ = [];
  8. this.ackID = 0;
  9. this.ondisconnect = () => {};
  10. this.onconnect = () => {};
  11. this.onmessage = () => {};
  12. this.createWS();
  13. }
  14. send(obj, cb) {
  15. return new Promise((resolve, reject) => {
  16. if (this.ready) {
  17. return this.reallySend(obj, resolve, reject);
  18. } else {
  19. this.sendQ.push([obj, resolve, reject]);
  20. }
  21. });
  22. }
  23. createWS() {
  24. if (this.sock)
  25. this.sock.close();
  26. this.sock = new WebSocket(this.url);
  27. this.sock.onopen = () => {
  28. this.ready = true;
  29. this.ackID = 0;
  30. for (let i = 0; i < this.sendQ.length; ++i)
  31. this.reallySend(...this.sendQ[i]);
  32. this.sendQ = [];
  33. this.onconnect();
  34. };
  35. this.sock.onclose = () => {
  36. console.error("Connection closed.");
  37. this.ready = false;
  38. this.sock = null;
  39. for (let i = 0; i < this.ackQ.length; ++i) {
  40. let [ resolve, reject ] = this.ackQ[i];
  41. reject("Lost connection.");
  42. }
  43. this.ackQ = [];
  44. this.ondisconnect();
  45. setTimeout(() => this.createWS(), 1000);
  46. };
  47. this.sock.onerror = evt => {
  48. console.error("WebSocket error:", evt);
  49. };
  50. this.sock.onmessage = evt => {
  51. let obj = JSON.parse(evt.data);
  52. if (obj.type == "ack") {
  53. let [ resolve, reject ] = this.ackQ[obj.ackID];
  54. if (obj.error)
  55. reject(obj.error);
  56. else
  57. resolve(obj);
  58. } else {
  59. this.onmessage(obj);
  60. }
  61. };
  62. }
  63. reallySend(obj, resolve, reject) {
  64. let ackID = this.ackID++;
  65. this.ackQ[ackID] = [ resolve, reject ];
  66. obj.ackID = ackID;
  67. this.sock.send(JSON.stringify(obj));
  68. }
  69. }