dataconnection.js 5.6 KB

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