reflector-client.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2014-2019 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  4. Virtual World Framework Apache 2.0 license (https://github.com/NikolaySuslov/livecodingspace/blob/master/licenses/LICENSE_VWF.md)
  5. */
  6. //import { Helpers } from '/helpers.js';
  7. class ReflectorClient {
  8. constructor() {
  9. console.log("reflector client constructor");
  10. this.helpers = _app.helpers; //new Helpers;
  11. this.socket = undefined;
  12. }
  13. connect(component_uri_or_json_or_object, path){
  14. function isSocketIO07() {
  15. //return ( parseFloat( io.version ) >= 0.7 );
  16. return true
  17. }
  18. try {
  19. let objToRef = this.helpers.reduceSaveObject(path);
  20. var options = {
  21. // The socket is relative to the application path.
  22. // resource: window.location.pathname.slice( 1,
  23. // window.location.pathname.lastIndexOf("/") ),
  24. query: {
  25. pathname: window.location.pathname.slice( 1,
  26. window.location.pathname.lastIndexOf("/") ),
  27. appRoot: "./public",
  28. path: JSON.stringify(objToRef)//JSON.stringify(path)
  29. },
  30. // query: 'pathname=' + window.location.pathname.slice( 1,
  31. // window.location.pathname.lastIndexOf("/") ),
  32. // Use a secure connection when the application comes from https.
  33. secure: window.location.protocol === "https:",
  34. // Don't attempt to reestablish lost connections. The client reloads after a
  35. // disconnection to recreate the application from scratch.
  36. //reconnect: false,
  37. reconnection: false,
  38. upgrade: false,
  39. transports: ['websocket']
  40. };
  41. if ( isSocketIO07() ) {
  42. //window.location.host
  43. var host = window._app.reflectorHost; //localStorage.getItem('lcs_reflector');
  44. //if(!host) host = 'http://localhost:3002'; //window.location.origin;
  45. this.socket = io.connect( host, options );
  46. } else { // Ruby Server -- only supports socket.io 0.6
  47. io.util.merge( options, {
  48. // For socket.io 0.6, specify the port since the default isn't correct when
  49. // using https.
  50. port: window.location.port ||
  51. ( window.location.protocol === "https:" ? 443 : 80 ),
  52. // The ruby socket.io server only supports WebSockets. Don't try the others.
  53. transports: [
  54. 'websocket',
  55. ],
  56. // Increase the timeout because of starvation while loading the scene. The
  57. // server timeout must also be increased. (For socket.io 0.7+, the client
  58. // timeout is controlled by the server.)
  59. transportOptions: {
  60. "websocket": { timeout: 90000 },
  61. },
  62. } );
  63. this.socket = io.connect( undefined, options );
  64. }
  65. } catch ( e ) {
  66. // If a connection to the reflector is not available, then run in single-user mode.
  67. // Messages intended for the reflector will loop directly back to us in this case.
  68. // Start a timer to monitor the incoming queue and dispatch the messages as though
  69. // they were received from the server.
  70. vwf.dispatch();
  71. setInterval( function() {
  72. var fields = {
  73. time: vwf.now + 0.010, // TODO: there will be a slight skew here since the callback intervals won't be exactly 10 ms; increment using the actual delta time; also, support play/pause/stop and different playback rates as with connected mode.
  74. origin: "reflector",
  75. };
  76. vwf.private.queue.insert( fields, true ); // may invoke dispatch(), so call last before returning to the host
  77. }, 10 );
  78. }
  79. if ( this.socket ) {
  80. this.socket.on('connect_error', function(err) {
  81. console.log(err);
  82. var errDiv = document.createElement("div");
  83. errDiv.innerHTML = "<div class='vwf-err' style='z-index: 10; position: absolute; top: 80px; right: 50px'>Connection error!" + err + "</div>";
  84. document.querySelector('body').appendChild(errDiv);
  85. });
  86. this.socket.on( "connect", function() {
  87. vwf.logger.infox( "-socket", "connected" );
  88. if ( isSocketIO07() ) {
  89. vwf.moniker_ = this.id;
  90. } else { //Ruby Server
  91. vwf.moniker_ = this.transport.sessionid;
  92. }
  93. } );
  94. // Configure a handler to receive messages from the server.
  95. // Note that this example code doesn't implement a robust parser capable of handling
  96. // arbitrary text and that the messages should be placed in a dedicated priority
  97. // queue for best performance rather than resorting the queue as each message
  98. // arrives. Additionally, overlapping messages may cause actions to be performed out
  99. // of order in some cases if messages are not processed on a single thread.
  100. this.socket.on( "message", function( message ) {
  101. // vwf.logger.debugx( "-socket", "message", message );
  102. try {
  103. if ( isSocketIO07() ) {
  104. var fields = message;
  105. } else { // Ruby Server - Unpack the arguements
  106. var fields = JSON.parse( message );
  107. }
  108. fields.time = Number( fields.time );
  109. // TODO: other message validation (check node id, others?)
  110. fields.origin = "reflector";
  111. // Update the queue. Messages in the queue are ordered by time, then by order of arrival.
  112. // Time is only advanced if the message has no action, meaning it is a tick.
  113. vwf.private.queue.insert( fields, !fields.action ); // may invoke dispatch(), so call last before returning to the host
  114. // Each message from the server allows us to move time forward. Parse the
  115. // timestamp from the message and call dispatch() to execute all queued
  116. // actions through that time, including the message just received.
  117. // The simulation may perform immediate actions at the current time or it
  118. // may post actions to the queue to be performed in the future. But we only
  119. // move time forward for items arriving in the queue from the reflector.
  120. } catch ( e ) {
  121. vwf.logger.warn( fields.action, fields.node, fields.member, fields.parameters,
  122. "exception performing action:", require( "vwf/utility" ).exceptionMessage( e ) );
  123. }
  124. } );
  125. this.socket.on( "disconnect", function() {
  126. vwf.logger.infox( "-socket", "disconnected" );
  127. // Reload to rejoin the application.
  128. window.location = window.location.href;
  129. } );
  130. this.socket.on( "error", function() {
  131. //Overcome by compatibility.js websockets check
  132. document.querySelector('body').innerHTML = "<div class='vwf-err'>WebSockets connections are currently being blocked. Please check your proxy server settings.</div>";
  133. // jQuery('body').html("<div class='vwf-err'>WebSockets connections are currently being blocked. Please check your proxy server settings.</div>");
  134. } );
  135. if ( !isSocketIO07() ) {
  136. // Start communication with the reflector.
  137. this.socket.connect(); // TODO: errors can occur here too, particularly if a local client contains the socket.io files but there is no server; do the loopback here instead of earlier in response to new io.Socket.
  138. }
  139. } else if ( component_uri_or_json_or_object ) {
  140. // Load the application. The application is rooted in a single node constructed here
  141. // as an instance of the component passed to initialize(). That component, its
  142. // prototype(s), and its children, and their prototypes and children, flesh out the
  143. // entire application.
  144. // TODO: add note that this is only for a self-determined application; with socket, wait for reflection server to tell us.
  145. // TODO: maybe depends on component_uri_or_json_or_object too; when to override and not connect to reflection server?
  146. this.createNode( component_uri_or_json_or_object, "application" );
  147. } else { // TODO: also do this if component_uri_or_json_or_object was invalid and createNode() failed
  148. // TODO: show a selection dialog
  149. }
  150. }
  151. }
  152. export { ReflectorClient }