dataconnection.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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; // TODO: metadata could also be a part of the paylod.
  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. // TODO: util.supports.binary
  42. if (util.supports.binary) {
  43. // Webkit doesn't support binary yet
  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. // TODO: util.supports.reliable
  53. if (!util.supports.reliable) {
  54. this._reliable = new Reliable(this._dc, util.debug);
  55. }
  56. if (this._reliable) {
  57. this._reliable.onmessage = function(msg) {
  58. self.emit('data', msg);
  59. };
  60. } else {
  61. this._dc.onmessage = function(e) {
  62. self._handleDataMessage(e);
  63. };
  64. }
  65. this._dc.onclose = function(e) {
  66. util.log('DataChannel closed for:', self.peer);
  67. // TODO: remove connection from Peer as well!!
  68. self.close();
  69. };
  70. }
  71. DataConnection.prototype._cleanup = function() {
  72. if (this._dc && this._dc.readyState !== 'closed') {
  73. this._dc.close();
  74. this._dc = null;
  75. }
  76. this.open = false;
  77. Negotiator.cleanup(this);
  78. this.emit('close');
  79. }
  80. // Handles a DataChannel message.
  81. DataConnection.prototype._handleDataMessage = function(e) {
  82. var self = this;
  83. var data = e.data;
  84. var datatype = data.constructor;
  85. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  86. if (datatype === Blob) {
  87. // Datatype should never be blob
  88. util.blobToArrayBuffer(data, function(ab) {
  89. data = util.unpack(ab);
  90. self.emit('data', data);
  91. });
  92. return;
  93. } else if (datatype === ArrayBuffer) {
  94. data = util.unpack(data);
  95. } else if (datatype === String) {
  96. // String fallback for binary data for browsers that don't support binary yet
  97. var ab = util.binaryStringToArrayBuffer(data);
  98. data = util.unpack(ab);
  99. }
  100. } else if (this.serialization === 'json') {
  101. data = JSON.parse(data);
  102. }
  103. this.emit('data', data);
  104. }
  105. /**
  106. * Exposed functionality for users.
  107. */
  108. /** Allows user to close connection. */
  109. DataConnection.prototype.close = function() {
  110. if (!this.open) {
  111. return;
  112. }
  113. this._cleanup();
  114. };
  115. /** Allows user to send data. */
  116. DataConnection.prototype.send = function(data) {
  117. if (!this.open) {
  118. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  119. }
  120. if (this._reliable) {
  121. // Note: reliable shim sending will make it so that you cannot customize
  122. // serialization.
  123. this._reliable.send(data);
  124. return;
  125. }
  126. var self = this;
  127. if (this.serialization === 'none') {
  128. this._dc.send(data);
  129. } else if (this.serialization === 'json') {
  130. this._dc.send(JSON.stringify(data));
  131. } else {
  132. var utf8 = (this.serialization === 'binary-utf8');
  133. var blob = util.pack(data, utf8);
  134. // DataChannel currently only supports strings.
  135. if (!util.supports.binary) {
  136. util.blobToBinaryString(blob, function(str){
  137. self._dc.send(str);
  138. });
  139. } else {
  140. this._dc.send(blob);
  141. }
  142. }
  143. };
  144. DataConnection.prototype.handleMessage = function(message) {
  145. var payload = message.payload;
  146. switch (message.type) {
  147. case 'ANSWER':
  148. // TODO: assert sdp exists.
  149. // Should we pass `this`?
  150. // Forward to negotiator
  151. Negotiator.handleSDP(message.type, this, payload.sdp);
  152. break;
  153. case 'CANDIDATE':
  154. // TODO
  155. Negotiator.handleCandidate(this, payload.candidate);
  156. break;
  157. default:
  158. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  159. break;
  160. }
  161. }