Socket.js 951 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. class Socket {
  2. constructor(path) {
  3. const url = this.url = new Url();
  4. if(url.getProtocol() === 'https:')
  5. url.setProtocol('wss');
  6. else
  7. url.setProtocol('ws');
  8. url.setPath(path).setHash();
  9. try {
  10. this.connection = new WebSocket(url.toString());
  11. this.keepAlive = setInterval(() => {
  12. this.connection.send('keep-alive');
  13. }, 20000);
  14. this.connection.onclose = (e) => {
  15. clearInterval(this.keepAlive);
  16. };
  17. } catch(e) {
  18. this.connection = null;
  19. }
  20. }
  21. onOpen(onopen) {
  22. if(this.connection)
  23. this.connection.onopen = onopen;
  24. return this;
  25. }
  26. onMessage(onmessage) {
  27. if(this.connection)
  28. this.connection.onmessage = onmessage;
  29. return this;
  30. }
  31. onError(onerror) {
  32. if(this.connection)
  33. this.connection.onerror = onerror;
  34. return this;
  35. }
  36. onClose(onclose) {
  37. if(this.connection)
  38. this.connection.onclose = (e) => {
  39. clearInterval(this.keepAlive);
  40. onclose(e);
  41. };
  42. return this;
  43. }
  44. }