socket.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. var data;
  71. try {
  72. data = JSON.parse(event.data);
  73. } catch(e) {
  74. data = event.data;
  75. }
  76. if (data.constructor == Object) {
  77. self.emit('message', data);
  78. } else {
  79. util.log('Invalid server message', event.data);
  80. }
  81. };
  82. // Take care of the queue of connections if necessary and make sure Peer knows
  83. // socket is open.
  84. this._socket.onopen = function() {
  85. util.log('Socket open');
  86. if (self._id) {
  87. self.emit('open');
  88. }
  89. };
  90. };
  91. /** Start XHR streaming. */
  92. Socket.prototype._startXhrStream = function() {
  93. try {
  94. var self = this;
  95. var http = new XMLHttpRequest();
  96. var url = this._httpUrl + '/id';
  97. // Set API key if necessary.
  98. if (!!this._key) {
  99. url += '/' + this._key;
  100. }
  101. http.open('post', url, true);
  102. http.setRequestHeader('Content-Type', 'application/json');
  103. http.onreadystatechange = function() {
  104. self._handleStream(http);
  105. };
  106. http.send(JSON.stringify({ id: this._id }));
  107. } catch(e) {
  108. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  109. }
  110. };
  111. /** Handles onreadystatechange response as a stream. */
  112. Socket.prototype._handleStream = function(http, pad) {
  113. // 3 and 4 are loading/done state. All others are not relevant.
  114. if (http.readyState < 3) {
  115. return;
  116. } else if (http.readyState == 3 && http.status != 200) {
  117. return;
  118. }
  119. if (this._index === undefined) {
  120. // TODO
  121. this._index = 2;
  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 + '/' + type.toLowerCase();
  173. // Set API key if necessary.
  174. if (!!this._key) {
  175. url += '/' + this._key;
  176. }
  177. http.open('post', url, true);
  178. http.setRequestHeader('Content-Type', 'application/json');
  179. http.send(message);
  180. }
  181. };
  182. Socket.prototype.close = function() {
  183. if (!!this._socket && this._socket.readyState == 1) {
  184. this._socket.close();
  185. }
  186. };
  187. Socket.prototype.start = function() {
  188. this._checkIn();
  189. };