dataconnection.js 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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: true
  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. // Webkit doesn't support binary yet
  40. this._dc.binaryType = 'arraybuffer';
  41. }
  42. this._dc.onopen = function() {
  43. util.log('Data channel connection success');
  44. self.open = true;
  45. self.emit('open');
  46. }
  47. // Use the Reliable shim for non Firefox browsers
  48. if (!util.supports.reliable && this.reliable) {
  49. this._reliable = new Reliable(this._dc, util.debug);
  50. }
  51. if (this._reliable) {
  52. this._reliable.onmessage = function(msg) {
  53. self.emit('data', msg);
  54. };
  55. } else {
  56. this._dc.onmessage = function(e) {
  57. self._handleDataMessage(e);
  58. };
  59. }
  60. this._dc.onclose = function(e) {
  61. util.log('DataChannel closed for:', self.peer);
  62. self.close();
  63. };
  64. }
  65. // Handles a DataChannel message.
  66. DataConnection.prototype._handleDataMessage = function(e) {
  67. var self = this;
  68. var data = e.data;
  69. var datatype = data.constructor;
  70. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  71. if (datatype === Blob) {
  72. // Datatype should never be blob
  73. util.blobToArrayBuffer(data, function(ab) {
  74. data = util.unpack(ab);
  75. self.emit('data', data);
  76. });
  77. return;
  78. } else if (datatype === ArrayBuffer) {
  79. data = util.unpack(data);
  80. } else if (datatype === String) {
  81. // String fallback for binary data for browsers that don't support binary yet
  82. var ab = util.binaryStringToArrayBuffer(data);
  83. data = util.unpack(ab);
  84. }
  85. } else if (this.serialization === 'json') {
  86. data = JSON.parse(data);
  87. }
  88. this.emit('data', data);
  89. }
  90. /**
  91. * Exposed functionality for users.
  92. */
  93. /** Allows user to close connection. */
  94. DataConnection.prototype.close = function() {
  95. if (!this.open) {
  96. return;
  97. }
  98. this.open = false;
  99. Negotiator.cleanup(this);
  100. this.emit('close');
  101. }
  102. /** Allows user to send data. */
  103. DataConnection.prototype.send = function(data) {
  104. if (!this.open) {
  105. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  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 {
  125. this._dc.send(blob);
  126. }
  127. } else {
  128. this._dc.send(data);
  129. }
  130. }
  131. DataConnection.prototype.handleMessage = function(message) {
  132. var payload = message.payload;
  133. switch (message.type) {
  134. case 'ANSWER':
  135. // Forward to negotiator
  136. Negotiator.handleSDP(message.type, this, payload.sdp);
  137. break;
  138. case 'CANDIDATE':
  139. Negotiator.handleCandidate(this, payload.candidate);
  140. break;
  141. default:
  142. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  143. break;
  144. }
  145. }