dataconnection.js 6.9 KB

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