dataconnection.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. }, 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. Negotiator.startConnection(
  22. this,
  23. this.options._payload || {
  24. originator: true,
  25. multiplex: this.options.multiplex // I don't think multiplex should be a
  26. // top-level property because it only
  27. // applies to the originator--otherwise
  28. // we'd just have an options.pc to use.
  29. }
  30. );
  31. }
  32. util.inherits(DataConnection, EventEmitter);
  33. DataConnection._idPrefix = 'dc_';
  34. /** Called by the Negotiator when the DataChannel is ready. */
  35. DataConnection.prototype.initialize = function(dc) {
  36. this._dc = dc;
  37. this._configureDataChannel();
  38. }
  39. DataConnection.prototype._configureDataChannel = function() {
  40. var self = this;
  41. if (util.supports.binary) {
  42. // Webkit doesn't support binary yet
  43. this._dc.binaryType = 'arraybuffer';
  44. }
  45. this._dc.onopen = function() {
  46. util.log('Data channel connection success');
  47. self.open = true;
  48. self.emit('open');
  49. }
  50. // Use the Reliable shim for non Firefox browsers
  51. if (!util.supports.reliable) {
  52. this._reliable = new Reliable(this._dc, util.debug);
  53. }
  54. if (this._reliable) {
  55. this._reliable.onmessage = function(msg) {
  56. self.emit('data', msg);
  57. };
  58. } else {
  59. this._dc.onmessage = function(e) {
  60. self._handleDataMessage(e);
  61. };
  62. }
  63. this._dc.onclose = function(e) {
  64. util.log('DataChannel closed for:', self.peer);
  65. self.close();
  66. };
  67. }
  68. DataConnection.prototype._cleanup = function() {
  69. // readyState is deprecated but still exists in older versions.
  70. if (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed') {
  71. this.pc.close();
  72. this.open = false;
  73. Negotiator.cleanup(this);
  74. this.emit('close');
  75. } else {
  76. this.emit('error', new Error('The connection has already been closed'));
  77. }
  78. }
  79. // Handles a DataChannel message.
  80. DataConnection.prototype._handleDataMessage = function(e) {
  81. var self = this;
  82. var data = e.data;
  83. var datatype = data.constructor;
  84. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  85. if (datatype === Blob) {
  86. // Datatype should never be blob
  87. util.blobToArrayBuffer(data, function(ab) {
  88. data = util.unpack(ab);
  89. self.emit('data', data);
  90. });
  91. return;
  92. } else if (datatype === ArrayBuffer) {
  93. data = util.unpack(data);
  94. } else if (datatype === String) {
  95. // String fallback for binary data for browsers that don't support binary yet
  96. var ab = util.binaryStringToArrayBuffer(data);
  97. data = util.unpack(ab);
  98. }
  99. } else if (this.serialization === 'json') {
  100. data = JSON.parse(data);
  101. }
  102. this.emit('data', data);
  103. }
  104. /**
  105. * Exposed functionality for users.
  106. */
  107. /** Allows user to close connection. */
  108. DataConnection.prototype.close = function() {
  109. if (!this.open) {
  110. return;
  111. }
  112. this._cleanup();
  113. }
  114. /** Allows user to send data. */
  115. DataConnection.prototype.send = function(data) {
  116. if (!this.open) {
  117. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  118. }
  119. if (this._reliable) {
  120. // Note: reliable shim sending will make it so that you cannot customize
  121. // serialization.
  122. this._reliable.send(data);
  123. return;
  124. }
  125. var self = this;
  126. if (this.serialization === 'none') {
  127. this._dc.send(data);
  128. } else if (this.serialization === 'json') {
  129. this._dc.send(JSON.stringify(data));
  130. } else {
  131. var utf8 = (this.serialization === 'binary-utf8');
  132. var blob = util.pack(data, utf8);
  133. // DataChannel currently only supports strings.
  134. if (!util.supports.binary) {
  135. util.blobToBinaryString(blob, function(str){
  136. self._dc.send(str);
  137. });
  138. } else {
  139. this._dc.send(blob);
  140. }
  141. }
  142. }
  143. DataConnection.prototype.handleMessage = function(message) {
  144. var payload = message.payload;
  145. switch (message.type) {
  146. case 'ANSWER':
  147. // Forward to negotiator
  148. Negotiator.handleSDP(message.type, this, payload.sdp);
  149. break;
  150. case 'CANDIDATE':
  151. Negotiator.handleCandidate(this, payload.candidate);
  152. break;
  153. default:
  154. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  155. break;
  156. }
  157. }