dataconnection.js 6.4 KB

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