socket.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /**
  2. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  3. * possible connection for peers.
  4. */
  5. function Socket(server, id, key) {
  6. if (!(this instanceof Socket)) return new Socket(server, id, key);
  7. EventEmitter.call(this);
  8. this._id = id;
  9. this._server = server;
  10. this._httpUrl = 'http://' + this._server;
  11. this._key = key;
  12. };
  13. util.inherits(Socket, EventEmitter);
  14. /** Check in with ID or get one from server. */
  15. Socket.prototype._checkIn = function() {
  16. // If no ID provided, get a unique ID from server.
  17. var self = this;
  18. if (!this._id) {
  19. try {
  20. var http = new XMLHttpRequest();
  21. var url = this._httpUrl + '/id';
  22. // Set API key if necessary.
  23. if (!!this._key)
  24. url += '/' + this._key;
  25. // If there's no ID we need to wait for one before trying to init socket.
  26. http.open('get', url, true);
  27. http.onreadystatechange = function() {
  28. if (!self._id && http.readyState > 2 && !!http.responseText) {
  29. try {
  30. var response = JSON.parse(http.responseText.split('\n').shift());
  31. if (!!response.id) {
  32. self._id = response.id;
  33. self._startWebSocket();
  34. self.emit('message', { type: 'ID', id: self._id });
  35. }
  36. } catch (e) {
  37. self._startWebSocket();
  38. }
  39. }
  40. self._handleStream(http, true);
  41. };
  42. http.send(null);
  43. } catch(e) {
  44. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  45. this._startWebSocket();
  46. }
  47. } else {
  48. this._startXhrStream();
  49. this._startWebSocket();
  50. }
  51. };
  52. /** Start up websocket communications. */
  53. Socket.prototype._startWebSocket = function() {
  54. if (!!this._socket)
  55. return;
  56. var wsurl = 'ws://' + this._server + '/ws';
  57. if (!!this._id) {
  58. wsurl += '?id=' + this._id;
  59. if (!!this._key)
  60. wsurl += '&key=' + this._key;
  61. } else if (!!this._key) {
  62. wsurl += '?key=' + this._key;
  63. }
  64. this._socket = new WebSocket(wsurl);
  65. var self = this;
  66. this._socket.onmessage = function(event) {
  67. try {
  68. self.emit('message', JSON.parse(event.data));
  69. } catch(e) {
  70. util.log('Invalid server message');
  71. }
  72. };
  73. // Take care of the queue of connections if necessary and make sure Peer knows
  74. // socket is open.
  75. this._socket.onopen = function() {
  76. util.log('Socket open');
  77. if (self._id) {
  78. self.emit('open');
  79. }
  80. };
  81. };
  82. /** Start XHR streaming. */
  83. Socket.prototype._startXhrStream = function() {
  84. try {
  85. var self = this;
  86. var http = new XMLHttpRequest();
  87. var url = this._httpUrl + '/id';
  88. // Set API key if necessary.
  89. if (!!this._key)
  90. url += '/' + this._key;
  91. http.open('post', url, true);
  92. http.setRequestHeader('Content-Type', 'application/json');
  93. http.onreadystatechange = function() {
  94. self._handleStream(http);
  95. };
  96. http.send(JSON.stringify({ id: this._id }));
  97. } catch(e) {
  98. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  99. }
  100. };
  101. /** Handles onreadystatechange response as a stream. */
  102. Socket.prototype._handleStream = function(http, pad) {
  103. // 3 and 4 are loading/done state. All others are not relevant.
  104. if (http.readyState < 3) {
  105. return;
  106. } else if (http.readyState == 3 && http.status != 200) {
  107. return;
  108. }
  109. if (this._index === undefined)
  110. this._index = pad ? 2 : 1;
  111. if (http.responseText === null)
  112. return;
  113. var message = http.responseText.split('\n')[this._index];
  114. if (!!message && http.readyState == 3) {
  115. this._index += 1;
  116. try {
  117. this._handleHTTPErrors(JSON.parse(message));
  118. } catch(e) {
  119. util.log('Invalid server message');
  120. }
  121. } else if (http.readyState == 4) {
  122. this._index = 1;
  123. }
  124. };
  125. Socket.prototype._handleHTTPErrors = function(message) {
  126. switch (message.type) {
  127. // XHR stream closed by timeout.
  128. case 'HTTP-END':
  129. util.log('XHR stream timed out.');
  130. if (!!this._socket && this._socket.readyState != 1)
  131. this._startXhrStream();
  132. break;
  133. // XHR stream closed by socket connect.
  134. case 'HTTP-SOCKET':
  135. util.log('XHR stream closed, WebSocket connected.');
  136. break;
  137. case 'HTTP-ERROR':
  138. this.emit('error', 'Something went wrong.');
  139. break;
  140. default:
  141. this.emit('message', message);
  142. }
  143. };
  144. /** Exposed send for DC & Peer. */
  145. Socket.prototype.send = function(data) {
  146. var type = data.type;
  147. message = JSON.stringify(data);
  148. if (!type) {
  149. this.emit('error', 'Invalid message');
  150. }
  151. if (!!this._socket && this._socket.readyState == 1) {
  152. this._socket.send(message);
  153. } else {
  154. var self = this;
  155. var http = new XMLHttpRequest();
  156. var url = this._httpUrl + '/' + type.toLowerCase();
  157. // Set API key if necessary.
  158. if (!!this._key)
  159. url += '/' + this._key;
  160. http.open('post', url, true);
  161. http.setRequestHeader('Content-Type', 'application/json');
  162. http.onload = function() {
  163. // This happens if destination peer is not available...
  164. if (http.responseText != 'OK') {
  165. self.emit('unavailable', data.dst)
  166. }
  167. }
  168. http.send(message);
  169. }
  170. };
  171. Socket.prototype.close = function() {
  172. if (!!this._socket && this._socket.readyState == 1) {
  173. this._socket.close();
  174. }
  175. };
  176. Socket.prototype.start = function() {
  177. this._checkIn();
  178. };