dataconnection.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * Wraps a DataChannel between two Peers.
  3. */
  4. function DataConnection(peer, provider, options) {
  5. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  6. EventEmitter.call(this);
  7. // TODO: perhaps default serialization should be binary-utf8?
  8. this.options = util.extend({
  9. serialization: 'binary',
  10. reliable: false
  11. }, options);
  12. // Connection is not open yet.
  13. this.open = false;
  14. this.type = 'data';
  15. this.peer = peer;
  16. this.provider = provider;
  17. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  18. this.label = this.options.label || this.id;
  19. this.metadata = this.options.metadata;
  20. this.serialization = this.options.serialization;
  21. this.reliable = this.options.reliable;
  22. // Data channel buffering.
  23. this._buffer = [];
  24. this._buffering = false;
  25. this.bufferSize = 0;
  26. // For storing large data.
  27. this._chunkedData = {};
  28. if (this.options._payload) {
  29. this._peerBrowser = this.options._payload.browser;
  30. this._peerSupports = this.options._payload.supports;
  31. }
  32. Negotiator.startConnection(
  33. this,
  34. this.options._payload || {
  35. originator: true
  36. }
  37. );
  38. }
  39. util.inherits(DataConnection, EventEmitter);
  40. DataConnection._idPrefix = 'dc_';
  41. /** Called by the Negotiator when the DataChannel is ready. */
  42. DataConnection.prototype.initialize = function(dc) {
  43. this._dc = this.dataChannel = dc;
  44. this._configureDataChannel();
  45. }
  46. DataConnection.prototype._configureDataChannel = function() {
  47. var self = this;
  48. if (util.supports.sctp) {
  49. this._dc.binaryType = 'arraybuffer';
  50. }
  51. this._dc.onopen = function() {
  52. util.log('Data channel connection success');
  53. self.open = true;
  54. self.emit('open');
  55. }
  56. // Use the Reliable shim for non Firefox browsers
  57. if (!util.supports.sctp && this.reliable) {
  58. this._reliable = new Reliable(this._dc, util.debug);
  59. }
  60. if (this._reliable) {
  61. this._reliable.onmessage = function(msg) {
  62. self.emit('data', msg);
  63. };
  64. } else {
  65. this._dc.onmessage = function(e) {
  66. self._handleDataMessage(e);
  67. };
  68. }
  69. this._dc.onclose = function(e) {
  70. util.log('DataChannel closed for:', self.peer);
  71. self.close();
  72. };
  73. }
  74. // Handles a DataChannel message.
  75. DataConnection.prototype._handleDataMessage = function(e) {
  76. var self = this;
  77. var data = e.data;
  78. var datatype = data.constructor;
  79. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  80. if (datatype === Blob) {
  81. // Datatype should never be blob
  82. util.blobToArrayBuffer(data, function(ab) {
  83. data = util.unpack(ab);
  84. self.emit('data', data);
  85. });
  86. return;
  87. } else if (datatype === ArrayBuffer) {
  88. data = util.unpack(data);
  89. } else if (datatype === String) {
  90. // String fallback for binary data for browsers that don't support binary yet
  91. var ab = util.binaryStringToArrayBuffer(data);
  92. data = util.unpack(ab);
  93. }
  94. } else if (this.serialization === 'json') {
  95. data = JSON.parse(data);
  96. }
  97. // Check if we've chunked--if so, piece things back together.
  98. // We're guaranteed that this isn't 0.
  99. if (data.__peerData) {
  100. var id = data.__peerData;
  101. var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total};
  102. chunkInfo.data[data.n] = data.data;
  103. chunkInfo.count += 1;
  104. if (chunkInfo.total === chunkInfo.count) {
  105. // We've received all the chunks--time to construct the complete data.
  106. data = new Blob(chunkInfo.data);
  107. this._handleDataMessage({data: data});
  108. // We can also just delete the chunks now.
  109. delete this._chunkedData[id];
  110. }
  111. this._chunkedData[id] = chunkInfo;
  112. return;
  113. }
  114. this.emit('data', data);
  115. }
  116. /**
  117. * Exposed functionality for users.
  118. */
  119. /** Allows user to close connection. */
  120. DataConnection.prototype.close = function() {
  121. if (!this.open) {
  122. return;
  123. }
  124. this.open = false;
  125. Negotiator.cleanup(this);
  126. this.emit('close');
  127. }
  128. /** Allows user to send data. */
  129. DataConnection.prototype.send = function(data, chunked) {
  130. if (!this.open) {
  131. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  132. return;
  133. }
  134. if (this._reliable) {
  135. // Note: reliable shim sending will make it so that you cannot customize
  136. // serialization.
  137. this._reliable.send(data);
  138. return;
  139. }
  140. var self = this;
  141. if (this.serialization === 'json') {
  142. this._bufferedSend(JSON.stringify(data));
  143. } else if ('binary-utf8'.indexOf(this.serialization) !== -1) {
  144. var utf8 = (this.serialization === 'binary-utf8');
  145. var blob = util.pack(data, utf8);
  146. // For Chrome-Firefox interoperability, we need to make Firefox "chunk"
  147. // the data it sends out.
  148. var needsChunking = util.chunkedBrowsers[this._peerBrowser] || util.chunkedBrowsers[util.browser];
  149. if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
  150. this._sendChunks(blob);
  151. return;
  152. }
  153. // DataChannel currently only supports strings.
  154. if (!util.supports.sctp) {
  155. util.blobToBinaryString(blob, function(str) {
  156. self._bufferedSend(str);
  157. });
  158. } else if (!util.supports.binaryBlob) {
  159. // We only do this if we really need to (e.g. blobs are not supported),
  160. // because this conversion is costly.
  161. util.blobToArrayBuffer(blob, function(ab) {
  162. self._bufferedSend(ab);
  163. });
  164. } else {
  165. this._bufferedSend(blob);
  166. }
  167. } else {
  168. this._bufferedSend(data);
  169. }
  170. }
  171. DataConnection.prototype._bufferedSend = function(msg) {
  172. if (this._buffering || !this._trySend(msg)) {
  173. this._buffer.push(msg);
  174. this.bufferSize = this._buffer.length;
  175. }
  176. }
  177. // Returns true if the send succeeds.
  178. DataConnection.prototype._trySend = function(msg) {
  179. try {
  180. this._dc.send(msg);
  181. } catch (e) {
  182. this._buffering = true;
  183. var self = this;
  184. setTimeout(function() {
  185. // Try again.
  186. self._buffering = false;
  187. self._tryBuffer();
  188. }, 100);
  189. return false;
  190. }
  191. return true;
  192. }
  193. // Try to send the first message in the buffer.
  194. DataConnection.prototype._tryBuffer = function() {
  195. if (this._buffer.length === 0) {
  196. return;
  197. }
  198. var msg = this._buffer[0];
  199. if (this._trySend(msg)) {
  200. this._buffer.shift();
  201. this.bufferSize = this._buffer.length;
  202. this._tryBuffer();
  203. }
  204. }
  205. DataConnection.prototype._sendChunks = function(blob) {
  206. var blobs = util.chunk(blob);
  207. for (var i = 0, ii = blobs.length; i < ii; i += 1) {
  208. var blob = blobs[i];
  209. this.send(blob, true);
  210. }
  211. }
  212. DataConnection.prototype.handleMessage = function(message) {
  213. var payload = message.payload;
  214. switch (message.type) {
  215. case 'ANSWER':
  216. this._peerBrowser = payload.browser;
  217. this._peerSupports = payload.supports;
  218. // Forward to negotiator
  219. Negotiator.handleSDP(message.type, this, payload.sdp);
  220. break;
  221. case 'CANDIDATE':
  222. Negotiator.handleCandidate(this, payload.candidate);
  223. break;
  224. default:
  225. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  226. break;
  227. }
  228. }