dataconnection.js 4.5 KB

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