dataconnection.js 6.8 KB

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