123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373 |
- /**
- * A DataChannel|PeerConnection between two Peers.
- */
- function DataConnection(id, peer, socket, options) {
- if (!(this instanceof DataConnection)) return new DataConnection(options);
- EventEmitter.call(this);
- options = util.extend({
- config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
- reliable: false,
- serialization: 'binary'
- }, options);
- this._options = options;
- // Connection is not open yet.
- this.open = false;
- this.id = id;
- this.peer = peer;
- this.metadata = options.metadata;
- this.serialization = options.serialization;
- this._originator = (options.sdp === undefined);
- this._socket = socket;
- this._sdp = options.sdp;
- if (!!this.id) {
- this.initialize();
- }
- };
- util.inherits(DataConnection, EventEmitter);
- DataConnection.prototype.initialize = function(id, socket) {
- if (!!id) {
- this.id = id;
- }
- if (!!socket) {
- this._socket = socket;
- }
- // Firefoxism: connectDataConnection ports.
- /*if (util.browserisms === 'Firefox') {
- this._firefoxPortSetup();
- }*/
- // Set up PeerConnection.
- this._startPeerConnection();
- // Listen for ICE candidates
- this._setupIce();
- // Listen for negotiation needed
- // ** Chrome only.
- if (util.browserisms !== 'Firefox' && !!this.id) {
- this._setupOffer();
- }
- // Listen for or create a data channel
- this._setupDataChannel();
- var self = this;
- if (!!this._sdp) {
- this.handleSDP(this._sdp, 'OFFER');
- }
- // Makes offer if Firefox
- /*if (util.browserisms === 'Firefox') {
- this._firefoxAdditional();
- }*/
- // No-op this.
- this.initialize = function() {};
- };
- DataConnection.prototype._setupOffer = function() {
- var self = this;
- util.log('Listening for `negotiationneeded`');
- this._pc.onnegotiationneeded = function() {
- util.log('`negotiationneeded` triggered');
- self._makeOffer();
- };
- };
- DataConnection.prototype._setupDataChannel = function() {
- var self = this;
- if (this._originator) {
- util.log('Creating data channel');
- // FOR NOW: reliable DC is not supported.
- this._dc = this._pc.createDataChannel(this.peer, { reliable: false });
- // Experimental reliable wrapper.
- if (this._options.reliable) {
- this._reliable = new Reliable(this._dc, util.debug);
- }
- this._configureDataChannel();
- } else {
- util.log('Listening for data channel');
- this._pc.ondatachannel = function(evt) {
- util.log('Received data channel');
- self._dc = evt.channel;
- // Experimental reliable wrapper.
- if (self._options.reliable) {
- self._reliable = new Reliable(self._dc, util.debug);
- }
- self._configureDataChannel();
- };
- }
- };
- /** Starts a PeerConnection and sets up handlers. */
- DataConnection.prototype._startPeerConnection = function() {
- util.log('Creating RTCPeerConnection');
- this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
- };
- /** Takes care of ice handlers. */
- DataConnection.prototype._setupIce = function() {
- util.log('Listening for ICE candidates');
- var self = this;
- this._pc.onicecandidate = function(evt) {
- if (evt.candidate) {
- util.log('Received ICE candidates');
- self._socket.send({
- type: 'CANDIDATE',
- payload: {
- candidate: evt.candidate
- },
- dst: self.peer
- });
- }
- };
- };
- /*DataConnection.prototype._firefoxPortSetup = function() {
- if (!DataConnection.usedPorts) {
- DataConnection.usedPorts = [];
- }
- this.localPort = util.randomPort();
- while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
- this.localPort = util.randomPort();
- }
- this.remotePort = util.randomPort();
- while (this.remotePort === this.localPort ||
- DataConnection.usedPorts.indexOf(this.localPort) != -1) {
- this.remotePort = util.randomPort();
- }
- DataConnection.usedPorts.push(this.remotePort);
- DataConnection.usedPorts.push(this.localPort);
- }*/
- DataConnection.prototype._configureDataChannel = function() {
- var self = this;
-
- if (util.browserisms !== 'Webkit') {
- this._dc.binaryType = 'arraybuffer';
- }
- this._dc.onopen = function() {
- util.log('Data channel connection success');
- self.open = true;
- self.emit('open');
- };
- if (this._reliable) {
- this._reliable.onmessage = function(msg) {
- self.emit('data', msg);
- };
- } else {
- this._dc.onmessage = function(e) {
- self._handleDataMessage(e);
- };
- }
- this._dc.onclose = function(e) {
- self.emit('close');
- };
- };
- /** Decide whether to handle Firefoxisms. */
- /*DataConnection.prototype._firefoxAdditional = function() {
- var self = this;
- getUserMedia({ audio: true, fake: true }, function(s) {
- self._pc.addStream(s);
- if (self._originator) {
- self._makeOffer();
- }
- }, function(err) { util.log('Could not getUserMedia'); });
- };*/
- DataConnection.prototype._makeOffer = function() {
- var self = this;
- this._pc.createOffer(function(offer) {
- util.log('Created offer');
- self._pc.setLocalDescription(offer, function() {
- util.log('Set localDescription to offer');
- self._socket.send({
- type: 'OFFER',
- payload: {
- sdp: offer,
- serialization: self.serialization,
- metadata: self.metadata,
- reliable: self._options.reliable
- },
- dst: self.peer
- });
- }, function(err) {
- self.emit('error', err);
- util.log('Failed to setLocalDescription, ', err);
- });
- });
- };
- /** Create an answer for PC. */
- DataConnection.prototype._makeAnswer = function() {
- var self = this;
- this._pc.createAnswer(function(answer) {
- util.log('Created answer');
- self._pc.setLocalDescription(answer, function() {
- util.log('Set localDescription to answer');
- self._socket.send({
- type: 'ANSWER',
- payload: {
- sdp: answer
- },
- dst: self.peer
- });
- }, function(err) {
- self.emit('error', err);
- util.log('Failed to setLocalDescription, ', err)
- });
- }, function(err) {
- self.emit('error', err);
- util.log('Failed to create answer, ', err)
- });
- };
- DataConnection.prototype._cleanup = function() {
- if (!!this._dc && this._dc.readyState != 'closed') {
- this._dc.close();
- this._dc = null;
- }
- if (!!this._pc && this._pc.readyState != 'closed') {
- this._pc.close();
- this._pc = null;
- }
- };
- // Handles a DataChannel message.
- DataConnection.prototype._handleDataMessage = function(e) {
- var self = this;
- var data = e.data;
- var datatype = data.constructor;
- if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
- if (datatype === Blob) {
- util.blobToArrayBuffer(data, function(ab) {
- data = util.unpack(ab);
- self.emit('data', data);
- });
- return;
- } else if (datatype === ArrayBuffer) {
- data = util.unpack(data);
- } else if (datatype === String) {
- var ab = util.binaryStringToArrayBuffer(data);
- data = util.unpack(ab);
- }
- } else if (this.serialization === 'json') {
- data = JSON.parse(data);
- }
- this.emit('data', data);
- };
- /**
- * Exposed functionality for users.
- */
- /** Allows user to close connection. */
- DataConnection.prototype.close = function() {
- this._cleanup();
- var self = this;
- if (this.open) {
- this._socket.send({
- type: 'LEAVE',
- dst: self.peer
- });
- }
- this.open = false;
- this.emit('close', this.peer);
- };
- /** Allows user to send data. */
- DataConnection.prototype.send = function(data) {
- if (this._reliable) {
- // Note: reliable sending will make it so that you cannot customize
- // serialization.
- this._reliable.send(data);
- return;
- }
- var self = this;
- if (this.serialization === 'none') {
- this._dc.send(data);
- } else if (this.serialization === 'json') {
- this._dc.send(JSON.stringify(data));
- } else {
- var utf8 = (this.serialization === 'binary-utf8');
- var blob = util.pack(data, utf8);
- // DataChannel currently only supports strings.
- if (util.browserisms === 'Webkit') {
- util.blobToBinaryString(blob, function(str){
- self._dc.send(str);
- });
- } else {
- this._dc.send(blob);
- }
- }
- };
- DataConnection.prototype.handleSDP = function(sdp, type) {
- if (util.browserisms != 'Firefox') {
- sdp = new RTCSessionDescription(sdp);
- }
- var self = this;
- this._pc.setRemoteDescription(sdp, function() {
- util.log('Set remoteDescription: ' + type);
- // Firefoxism
- /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
- self._pc.connectDataConnection(self.localPort, self.remotePort);
- self._socket.send({
- type: 'PORT',
- dst: self.peer,
- payload: {
- remote: self.localPort,
- local: self.remotePort
- }
- });
- } else*/ if (type === 'OFFER') {
- self._makeAnswer();
- }
- }, function(err) {
- self.emit('error', err);
- util.log('Failed to setRemoteDescription, ', err);
- });
- };
- DataConnection.prototype.handleCandidate = function(message) {
- var candidate = new RTCIceCandidate(message.candidate);
- this._pc.addIceCandidate(candidate);
- util.log('Added ice candidate');
- };
- DataConnection.prototype.handleLeave = function() {
- util.log('Peer ' + this.peer + ' disconnected');
- this.close();
- };
- /*
- DataConnection.prototype.handlePort = function(message) {
- if (!DataConnection.usedPorts) {
- DataConnection.usedPorts = [];
- }
- DataConnection.usedPorts.push(message.local);
- DataConnection.usedPorts.push(message.remote);
- this._pc.connectDataConnection(message.local, message.remote);
- };
- */
|