socket.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. /** Start XHR streaming. */
  82. Socket.prototype._startXhrStream = function() {
  83. try {
  84. var self = this;
  85. var http = new XMLHttpRequest();
  86. var url = this._httpUrl + '/id';
  87. // Set API key if necessary.
  88. if (!!this._key)
  89. url += '/' + this._key;
  90. http.open('post', url, true);
  91. http.setRequestHeader('Content-Type', 'application/json');
  92. http.onreadystatechange = function() {
  93. self._handleStream(http);
  94. };
  95. http.send(JSON.stringify({ id: this._id }));
  96. } catch(e) {
  97. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  98. }
  99. };
  100. /** Handles onreadystatechange response as a stream. */
  101. Socket.prototype._handleStream = function(http, pad) {
  102. // 3 and 4 are loading/done state. All others are not relevant.
  103. if (http.readyState < 3) {
  104. return;
  105. } else if (http.readyState == 3 && http.status != 200) {
  106. return;
  107. }
  108. if (this._index === undefined)
  109. this._index = pad ? 2 : 1;
  110. if (http.responseText === null)
  111. return;
  112. var message = http.responseText.split('\n')[this._index];
  113. if (!!message && http.readyState == 3) {
  114. this._index += 1;
  115. try {
  116. this._handleHTTPErrors(JSON.parse(message));
  117. } catch(e) {
  118. util.log('Invalid server message');
  119. }
  120. } else if (http.readyState == 4) {
  121. this._index = 1;
  122. }
  123. };
  124. Socket.prototype._handleHTTPErrors = function(message) {
  125. switch (message.type) {
  126. // XHR stream closed by timeout.
  127. case 'HTTP-END':
  128. util.log('XHR stream timed out.');
  129. if (!!this._socket && this._socket.readyState != 1)
  130. this._startXhrStream();
  131. break;
  132. // XHR stream closed by socket connect.
  133. case 'HTTP-SOCKET':
  134. util.log('XHR stream closed, WebSocket connected.');
  135. break;
  136. case 'HTTP-ERROR':
  137. this.emit('error', 'Something went wrong.');
  138. break;
  139. default:
  140. this.emit('message', message);
  141. }
  142. };
  143. /** Exposed send for DC & Peer. */
  144. Socket.prototype.send = function(data) {
  145. var type = data.type;
  146. message = JSON.stringify(data);
  147. if (!type)
  148. this.emit('error', 'Invalid message');
  149. if (!!this._socket && this._socket.readyState == 1) {
  150. this._socket.send(message);
  151. } else {
  152. var self = this;
  153. var http = new XMLHttpRequest();
  154. var url = this._httpUrl + '/' + type.toLowerCase();
  155. // Set API key if necessary.
  156. if (!!this._key)
  157. url += '/' + this._key;
  158. http.open('post', url, true);
  159. http.setRequestHeader('Content-Type', 'application/json');
  160. http.onload = function() {
  161. // This happens if destination peer is not available...
  162. if (http.responseText != 'OK') {
  163. self.emit('unavailable', data.dst)
  164. }
  165. }
  166. http.send(message);
  167. }
  168. };
  169. Socket.prototype.close = function() {
  170. if (!!this._socket && this._socket.readyState == 1)
  171. this._socket.close();
  172. };
  173. Socket.prototype.start = function() {
  174. this._checkIn();
  175. };