socket.js 5.3 KB

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