relay.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @fileoverview Dynamic interface to MeshCentral2
  3. * @author Ylian Saint-Hilaire
  4. * @version v0.0.1
  5. */
  6. var createMeshConnection = function (connectionId) {
  7. var obj = {};
  8. obj.connectionId = connectionId;
  9. obj.state = 0;
  10. obj.websocket = null;
  11. obj.onStateChanged = null;
  12. obj.onData = null;
  13. obj.connect = function () {
  14. if (obj.state == 0) {
  15. obj.websocket = new WebSocket(window.location.protocol.replace('http', 'ws') + '//' + window.location.host + '/meshrelay.ashx?id=' + obj.connectionId);
  16. obj.websocket.binaryType = "arraybuffer";
  17. obj.websocket.onopen = function (e) { console.log('WebSocket Connected', e); };
  18. obj.websocket.onmessage = function (e) {
  19. console.log('WebSocket Message', e);
  20. if ((obj.state = 1) && (e.data == 'c')) {
  21. obj.state = 2;
  22. if (obj.onStateChanged) { onStateChanged(obj, 2); }
  23. console.log('WebSocket Peer Connection', e);
  24. obj.send('bob');
  25. } else {
  26. if (obj.onData != null) { obj.onData(obj, e.data); }
  27. }
  28. };
  29. obj.websocket.onclose = function (e) {
  30. console.log('WebSocket Closed', e);
  31. obj.state = 0;
  32. if (obj.onStateChanged) { onStateChanged(obj, 0); }
  33. };
  34. obj.websocket.onerror = function (e) { console.log('WebSocket Error', e); };
  35. obj.state = 1;
  36. if (obj.onStateChanged) { onStateChanged(obj, 1); }
  37. }
  38. return obj;
  39. };
  40. obj.send = function (data) {
  41. if ((obj.state == 2) && (obj.websocket != null)) { obj.websocket.send(data); }
  42. };
  43. return obj;
  44. }