dataconnection.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /**
  2. * Wraps a DataChannel between two Peers.
  3. */
  4. function DataConnection(peer, dc, options) {
  5. if (!(this instanceof DataConnection)) return new DataConnection(peer, dc, options);
  6. EventEmitter.call(this);
  7. options = util.extend({
  8. serialization: 'binary'
  9. }, options);
  10. // Connection is not open yet.
  11. this.open = false;
  12. this.label = options.label;
  13. this.metadata = options.metadata;
  14. this.serialization = options.serialization;
  15. this.peer = peer;
  16. this.reliable = options.reliable;
  17. this._dc = dc;
  18. if (!!this._dc) {
  19. this._configureDataChannel();
  20. }
  21. };
  22. util.inherits(DataConnection, EventEmitter);
  23. DataConnection.prototype._configureDataChannel = function() {
  24. var self = this;
  25. if (util.browserisms !== 'Webkit') {
  26. // Webkit doesn't support binary yet
  27. this._dc.binaryType = 'arraybuffer';
  28. }
  29. this._dc.onopen = function() {
  30. util.log('Data channel connection success');
  31. self.open = true;
  32. self.emit('open');
  33. };
  34. // Use the Reliable shim for non Firefox browsers
  35. if (this.reliable && util.browserisms !== 'Firefox') {
  36. this._reliable = new Reliable(this._dc, util.debug);
  37. }
  38. if (this._reliable) {
  39. this._reliable.onmessage = function(msg) {
  40. self.emit('data', msg);
  41. };
  42. } else {
  43. this._dc.onmessage = function(e) {
  44. self._handleDataMessage(e);
  45. };
  46. }
  47. this._dc.onclose = function(e) {
  48. util.log('DataChannel closed.');
  49. self.close();
  50. };
  51. };
  52. DataConnection.prototype._cleanup = function() {
  53. if (!!this._dc && this._dc.readyState !== 'closed') {
  54. this._dc.close();
  55. this._dc = null;
  56. }
  57. this.open = false;
  58. this.emit('close');
  59. };
  60. // Handles a DataChannel message.
  61. DataConnection.prototype._handleDataMessage = function(e) {
  62. var self = this;
  63. var data = e.data;
  64. var datatype = data.constructor;
  65. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  66. if (datatype === Blob) {
  67. // Datatype should never be blob
  68. util.blobToArrayBuffer(data, function(ab) {
  69. data = util.unpack(ab);
  70. self.emit('data', data);
  71. });
  72. return;
  73. } else if (datatype === ArrayBuffer) {
  74. data = util.unpack(data);
  75. } else if (datatype === String) {
  76. // String fallback for binary data for browsers that don't support binary yet
  77. var ab = util.binaryStringToArrayBuffer(data);
  78. data = util.unpack(ab);
  79. }
  80. } else if (this.serialization === 'json') {
  81. data = JSON.parse(data);
  82. }
  83. this.emit('data', data);
  84. };
  85. DataConnection.prototype.addDC = function(dc) {
  86. this._dc = dc;
  87. this._configureDataChannel();
  88. };
  89. /**
  90. * Exposed functionality for users.
  91. */
  92. /** Allows user to close connection. */
  93. DataConnection.prototype.close = function() {
  94. if (!this.open) {
  95. return;
  96. }
  97. this._cleanup();
  98. };
  99. /** Allows user to send data. */
  100. DataConnection.prototype.send = function(data) {
  101. if (!this.open) {
  102. this.emit('error', new Error('Connection no longer open.'));
  103. }
  104. if (this._reliable) {
  105. // Note: reliable sending will make it so that you cannot customize
  106. // serialization.
  107. this._reliable.send(data);
  108. return;
  109. }
  110. var self = this;
  111. if (this.serialization === 'none') {
  112. this._dc.send(data);
  113. } else if (this.serialization === 'json') {
  114. this._dc.send(JSON.stringify(data));
  115. } else {
  116. var utf8 = (this.serialization === 'binary-utf8');
  117. var blob = util.pack(data, utf8);
  118. // DataChannel currently only supports strings.
  119. if (util.browserisms === 'Webkit') {
  120. util.blobToBinaryString(blob, function(str){
  121. self._dc.send(str);
  122. });
  123. } else {
  124. this._dc.send(blob);
  125. }
  126. }
  127. };
  128. DataConnection.prototype.handleMessage = function(message) {
  129. var payload = message.payload;
  130. switch (message.type) {
  131. case 'OFFER':
  132. var options = {
  133. sdp: payload.sdp,
  134. labels: payload.labels,
  135. config: this.options.config
  136. };
  137. // Either forward to or create new manager
  138. if (!manager) {
  139. manager = this._createManager(managerId, peer, options);
  140. }
  141. manager.handleUpdate(options.labels);
  142. manager.handleSDP(payload.sdp, message.type, payload.call);
  143. break;
  144. case 'EXPIRE':
  145. peer.emit('error', new Error('Could not connect to peer ' + manager.peer));
  146. break;
  147. case 'ANSWER':
  148. // Forward to specific manager
  149. if (manager) {
  150. manager.handleSDP(payload.sdp, message.type);
  151. }
  152. break;
  153. case 'CANDIDATE':
  154. // Forward to specific manager
  155. if (manager) {
  156. manager.handleCandidate(payload);
  157. }
  158. break;
  159. case 'LEAVE':
  160. // Leave on all managers for a user
  161. if (this._managers[peer]) {
  162. var ids = Object.keys(this._managers[peer].managers);
  163. for (var i = 0; i < ids.length; i++) {
  164. this._managers[peer].managers[ids[i]].handleLeave();
  165. }
  166. }
  167. break;
  168. default:
  169. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  170. break;
  171. }
  172. }