dataconnection.js 4.7 KB

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