socket.js 5.1 KB

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