Our RTCPeerConnection shim, it should look like a normal PeerConection from the outside, but it actually delegates to our plugin.
774951
function (iceServers, options, plugin, ready) {
    var Proto = function PeerConnection () {},
        api = new Proto(),
        id = $.uuid(),
        hasLocalDescription = false,
        hasRemoteDescription = false,
        candidates = [],
        inited = false,
        deferMethods = [],
        events;

    plugin.addRef(api);

    events = {
      addstream: [],
      removestream: [],
      icecandidate: [],
      signalingstatechange: [],
      iceconnectionstatechange: []
    };

    var onAddIceCandidate = function onAddIceCandidate () {/* success */},

        onAddIceCandidateFailed = function onAddIceCandidateFailed (err) {
          OTPlugin.error('Failed to process candidate');
          OTPlugin.error(err);
        },

        processPendingCandidates = function processPendingCandidates () {
          for (var i=0; i<candidates.length; ++i) {
            plugin._.addIceCandidate(id, candidates[i], onAddIceCandidate, onAddIceCandidateFailed);
          }
        },


        deferMethod = function deferMethod (method) {
          return function() {
            if (inited === true) {
              return method.apply(api, arguments);
            }

            deferMethods.push([method, arguments]);
          };
        },

        processDeferredMethods = function processDeferredMethods () {
          var m;
          while ( (m = deferMethods.shift()) ) {
            m[0].apply(api, m[1]);
          }
        },

        triggerEvent = function triggerEvent (/* eventName [, arg1, arg2, ..., argN] */) {
          var args = Array.prototype.slice.call(arguments),
              eventName = args.shift();

          if (!events.hasOwnProperty(eventName)) {
            OTPlugin.error('PeerConnection does not have an event called: ' + eventName);
            return;
          }

          $.forEach(events[eventName], function(listener) {
            listener.apply(null, args);
          });
        },

        bindAndDelegateEvents = function bindAndDelegateEvents (events) {
          for (var name in events) {
            if (events.hasOwnProperty(name)) {
              events[name] = curryCallAsync(events[name]);
            }
          }

          plugin._.on(id, events);
        },

        addStream = function addStream (streamJson) {
          setTimeout(function() {
            var stream = MediaStream.fromJson(streamJson, plugin),
                event = {stream: stream, target: api};

            if (api.onaddstream && $.isFunction(api.onaddstream)) {
              $.callAsync(api.onaddstream, event);
            }

            triggerEvent('addstream', event);
          }, 3000);
        },

        removeStream = function removeStream (streamJson) {
          var stream = MediaStream.fromJson(streamJson, plugin),
              event = {stream: stream, target: api};

          if (api.onremovestream && $.isFunction(api.onremovestream)) {
            $.callAsync(api.onremovestream, event);
          }

          triggerEvent('removestream', event);
        },

        iceCandidate = function iceCandidate (candidateSdp, sdpMid, sdpMLineIndex) {
          var candidate = new OTPlugin.RTCIceCandidate({
            candidate: candidateSdp,
            sdpMid: sdpMid,
            sdpMLineIndex: sdpMLineIndex
          });

          var event = {candidate: candidate, target: api};

          if (api.onicecandidate && $.isFunction(api.onicecandidate)) {
            $.callAsync(api.onicecandidate, event);
          }

          triggerEvent('icecandidate', event);
        },

        signalingStateChange = function signalingStateChange (state) {
          api.signalingState = state;
          var event = {state: state, target: api};

          if (api.onsignalingstatechange &&
                  $.isFunction(api.onsignalingstatechange)) {
            $.callAsync(api.onsignalingstatechange, event);
          }

          triggerEvent('signalingstate', event);
        },

        iceConnectionChange = function iceConnectionChange (state) {
          api.iceConnectionState = state;
          var event = {state: state, target: api};

          if (api.oniceconnectionstatechange &&
                  $.isFunction(api.oniceconnectionstatechange)) {
            $.callAsync(api.oniceconnectionstatechange, event);
          }

          triggerEvent('iceconnectionstatechange', event);
        };

    api.createOffer = deferMethod(function (success, error, constraints) {
      OTPlugin.debug('createOffer', constraints);
      plugin._.createOffer(id, function(type, sdp) {
        success(new OTPlugin.RTCSessionDescription({
          type: type,
          sdp: sdp
        }));
      }, error, constraints || {});
    });

    api.createAnswer = deferMethod(function (success, error, constraints) {
      OTPlugin.debug('createAnswer', constraints);
      plugin._.createAnswer(id, function(type, sdp) {
        success(new OTPlugin.RTCSessionDescription({
          type: type,
          sdp: sdp
        }));
      }, error, constraints || {});
    });

    api.setLocalDescription = deferMethod( function (description, success, error) {
      OTPlugin.debug('setLocalDescription');

      plugin._.setLocalDescription(id, description, function() {
        hasLocalDescription = true;

        if (hasRemoteDescription) processPendingCandidates();
        if (success) success.call(null);
      }, error);
    });

    api.setRemoteDescription = deferMethod( function (description, success, error) {
      OTPlugin.debug('setRemoteDescription');

      plugin._.setRemoteDescription(id, description, function() {
        hasRemoteDescription = true;

        if (hasLocalDescription) processPendingCandidates();
        if (success) success.call(null);
      }, error);
    });

    api.addIceCandidate = deferMethod( function (candidate) {
      OTPlugin.debug('addIceCandidate');

      if (hasLocalDescription && hasRemoteDescription) {
        plugin._.addIceCandidate(id, candidate, onAddIceCandidate, onAddIceCandidateFailed);
      }
      else {
        candidates.push(candidate);
      }
    });

    api.addStream = deferMethod( function (stream) {
      var constraints = {};
      plugin._.addStream(id, stream, constraints);
    });

    api.removeStream = deferMethod( function (stream) {
      plugin._.removeStream(id, stream);
    });


    api.getRemoteStreams = function () {
      return $.map(plugin._.getRemoteStreams(id), function(stream) {
        return MediaStream.fromJson(stream, plugin);
      });
    };

    api.getLocalStreams = function () {
      return $.map(plugin._.getLocalStreams(id), function(stream) {
        return MediaStream.fromJson(stream, plugin);
      });
    };

    api.getStreamById = function (streamId) {
      return MediaStream.fromJson(plugin._.getStreamById(id, streamId), plugin);
    };

    api.getStats = deferMethod( function (mediaStreamTrack, success, error) {
      plugin._.getStats(id, mediaStreamTrack || null, curryCallAsync(function(statsReportJson) {
        var report = new RTCStatsReport(JSON.parse(statsReportJson));
        success(report);
      }), error);
    });

    api.close = function () {
      plugin._.destroyPeerConnection(id);
      plugin.removeRef(this);
    };

    api.destroy = function () {
      api.close();
    };

    api.addEventListener = function  (event, handler /* [, useCapture] we ignore this */) {
      if (events[event] === void 0) {
        OTPlugin.error('Could not bind invalid event "' + event + '" to PeerConnection. ' +
                        'The valid event types are:');
        OTPlugin.error('\t' + $.keys(events).join(', '));
        return;
      }

      events[event].push(handler);
    };

    api.removeEventListener = function  (event, handler /* [, useCapture] we ignore this */) {
      if (events[event] === void 0) {
        OTPlugin.error('Could not unbind invalid event "' + event + '" to PeerConnection. ' +
                        'The valid event types are:');
        OTPlugin.error('\t' + $.keys(events).join(', '));
        return;
      }

      events[event] = $.filter(events[event], handler);
    };

    // These should appear to be null, instead of undefined, if no
    // callbacks are assigned. This more closely matches how the native
    // objects appear and allows 'if (pc.onsignalingstatechange)' type
    // feature detection to work.
    api.onaddstream = null;
    api.onremovestream = null;
    api.onicecandidate = null;
    api.onsignalingstatechange = null;
    api.oniceconnectionstatechange = null;

    // Both username and credential must exist, otherwise the plugin throws an error
    $.forEach(iceServers.iceServers, function(iceServer) {
      if (!iceServer.username) iceServer.username = '';
      if (!iceServer.credential) iceServer.credential = '';
    });

    if (!plugin._.initPeerConnection(id, iceServers, options)) {
      ready(new $.error('Failed to initialise PeerConnection'));
      return;
    }

    // This will make sense once init becomes async
    bindAndDelegateEvents({
      addStream: addStream,
      removeStream: removeStream,
      iceCandidate: iceCandidate,
      signalingStateChange: signalingStateChange,
      iceConnectionChange: iceConnectionChange
    });

    inited = true;
    processDeferredMethods();
    ready(void 0, api);

    return api;
  }
418451
function initPeer(el) {
  var propValue = el.getAttribute('rtc-peer');
  var targetStream = el.getAttribute('rtc-stream');
  var peerRoles = propValue ? propValue.split(reSep) : ['*'];

  // create a data container that we will attach to the element
  var data = el._rtc || (el._rtc = {});

  function attachStream(stream) {
    debug('attaching stream');
    media(stream).render(el);
    data.streamId = stream.id;
  }

  function addStream(stream, peer) {
    // if we don't have a stream or already have a stream id then bail
    if (data.streamId) {
      return;
    }

    // if we have a particular target stream, then go looking for it
    if (targetStream) {
      debug('requesting stream data');
      sessionMgr.getStreamData(stream, function(data) {
        debug('got stream data', data);

        // if it's a match, then attach
        if (data && data.name === targetStream) {
          attachStream(stream);
        }
      });
    }
    // otherwise, automatically associate with the element
    else {
      attachStream(stream);
    }
  }

  // iterate through the peers and monitor events for that peer
  peerRoles.forEach(function(role) {
    eve.on('glue.peer.active.' + role, function(peer, peerId) {
      // if the element already has a peer, then do nothing
      if (data.peerId) {
        return;
      }

      debug('peer active', peer.getRemoteStreams());

      // associate the peer id with the element
      data.peerId = peerId;

      // add existing streams
      [].slice.call(peer.getRemoteStreams()).forEach(addStream);

      // listen for add stream events
      // NOTE: currently not in use as we have move to a non-reactive
      // coupling approach to ensure firefox compatibility
      // peer.addEventListener('addstream', function(evt) {
      //   addStream(evt.stream, peer);
      // });
    });
  });

  eve.on('glue.peer.leave', function(peer, peerId) {
    // if the peer leaving matches the remote peer, then cleanup
    if (data.peerId === peerId) {
      // reset the target media element
      resetEl(el);

      // reset the rtc data
      data = el._rtc = {};
    }
  });

  return el;
}
672639
function(config) {
  
    //console.log('RtcConnector: createMqttClient: server:  '+ config.server);

     var client = mqtt.connect(config.server + ':' + config.port);
     client.on('message', function(topic, message) {
       /*
        * This is called when a topic matching a valid subsription is received
        *   We have a valid subscription somewhere... 
        *   TODO:  This must call the filter FOR the topic and ensure it hasn't already
        *   been called.  
        */
       l('MESSAGE') && console.log('RtcConnector.mqttClient - Received Message on topic: '+topic);
        try {
          doFilter(topic,message);
        } catch(e) {
          console.error('MqttClient Message callback chain failure:',e);
          console.log(e.stack);
        }
      });
    client.on('connect', function(error) {
      console.log('RtcConnector: mqtt is CONNECTED');
      this.connected = true;
      this.emit('connected');
    }.bind(this));
    client.on('error', function(error) {
      console.log('RtcConnector: DISCONNECTED - error:'+ error);
      this.connected = false;
      this.emit('disconnected', error);
    }.bind(this));
    client.on('close', function(error) {
      console.log('RtcConnector: DISCONNECTED - close: '+error);
      this.connected = false;
      this.emit('disconnected',error);
    }.bind(this));
    return client;
  }
625193
public void peerConnectionDidOpenDataChannel(DataChannel newDataChannel) {
        if (null != dataChannel) {
            // Replacing the previous connection, so disable observer messages from the old instance
            dataChannel.unregisterObserver();
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                public void run() {
                    if (null != listenerReference) {
                        Listener listener = listenerReference.get();
                        if (null != listener) {
                            listener.onStart(RespokeDirectConnection.this);
                        }
                    }
                }
            });
        }

        dataChannel = newDataChannel;
        newDataChannel.registerObserver(this);
    }
960502
public void onConversationHidden(Peer peer) {
        if (visiblePeer != null && visiblePeer.equals(peer)) {
            this.visiblePeer = null;
        }
    }
903506
protected void customizeConnection(String pathInContext, String pathParams, HttpRequest request, Socket socket) throws IOException
    {
    }
1357590
function SipConnection(connection, connectCallback) {
    function isData(session) {
        return !session.audio && !session.video && !session.screen && session.data;
    }

    connection.socket = {
        send: function(data) {
            var remoteSipURI = data.remoteUserId + '@yourServer.com';
            sip.publish(remoteSipURI, data); // maybe JSON.stringify(data)
        }
    };

    // connect/subscribe to SIP here

    // ref: http://sipjs.com/demo-phone/
    // and: http://sipjs.com/demo-phone/js/ua.js
    var config = {
        userAgentString: 'SIP.js/0.7.0 BB',
        traceSip: true,
        register: false,
        displayName: '',
        uri: '', // connection.userid + '@yourServer.com'
        authorizationUser: '',
        password: '',
        wsServers: 'wss://edge.sip.onsip.com'
    };

    var sip = new SIP.UA(config);

    sip.on('invite', function(session) {
        // do the stuff!
    });

    sip.on('message', function(data) {
        data = JSON.parse(data);

        if (data.eventName === connection.socketMessageEvent) {
            onMessagesCallback(data.data);
        }

        if (data.eventName === 'presence') {
            data = data.data;
            if (data.userid === connection.userid) return;
            connection.onUserStatusChanged({
                userid: data.userid,
                status: data.isOnline === true ? 'online' : 'offline',
                extra: connection.peers[data.userid] ? connection.peers[data.userid].extra : {}
            });
        }
    });

    // connected or registered
    sip.on('connected', function() {
        if (connection.enableLogs) {
            console.info('SIP connection is opened.');
        }

        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: true
        });

        if (connectCallback) connectCallback(connection.socket);
    });

    sip.on('unregistered', function() {
        if (!connection.enableLogs) return;
        console.warn('Socket connection is closed.');
    });

    connection.socket.emit = function(eventName, data, callback) {
        if (eventName === 'changed-uuid') return;
        if (data.message && data.message.shiftedModerationControl) return;

        connection.socket.send({
            eventName: eventName,
            data: data
        });

        if (callback) {
            callback(true);
        }
    };

    var mPeer = connection.multiPeersHandler;

    function onMessagesCallback(message) {
        if (message.remoteUserId != connection.userid) return;

        if (connection.peers[message.sender] && connection.peers[message.sender].extra != message.message.extra) {
            connection.peers[message.sender].extra = message.message.extra;
            connection.onExtraDataUpdated({
                userid: message.sender,
                extra: message.message.extra
            });
        }

        if (message.message.streamSyncNeeded && connection.peers[message.sender]) {
            var stream = connection.streamEvents[message.message.streamid];
            if (!stream || !stream.stream) {
                return;
            }

            var action = message.message.action;

            if (action === 'ended' || action === 'stream-removed') {
                connection.onstreamended(stream);
                return;
            }

            var type = message.message.type != 'both' ? message.message.type : null;
            stream.stream[action](type);
            return;
        }

        if (message.message === 'connectWithAllParticipants') {
            if (connection.broadcasters.indexOf(message.sender) === -1) {
                connection.broadcasters.push(message.sender);
            }

            mPeer.onNegotiationNeeded({
                allParticipants: connection.getAllParticipants(message.sender)
            }, message.sender);
            return;
        }

        if (message.message === 'removeFromBroadcastersList') {
            if (connection.broadcasters.indexOf(message.sender) !== -1) {
                delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)];
                connection.broadcasters = removeNullEntries(connection.broadcasters);
            }
            return;
        }

        if (message.message === 'dropPeerConnection') {
            connection.deletePeer(message.sender);
            return;
        }

        if (message.message.allParticipants) {
            if (message.message.allParticipants.indexOf(message.sender) === -1) {
                message.message.allParticipants.push(message.sender);
            }

            message.message.allParticipants.forEach(function(participant) {
                mPeer[!connection.peers[participant] ? 'createNewPeer' : 'renegotiatePeer'](participant, {
                    localPeerSdpConstraints: {
                        OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    remotePeerSdpConstraints: {
                        OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                    isDataOnly: isData(connection.session)
                });
            });
            return;
        }

        if (message.message.newParticipant) {
            if (message.message.newParticipant == connection.userid) return;
            if (!!connection.peers[message.message.newParticipant]) return;

            mPeer.createNewPeer(message.message.newParticipant, message.message.userPreferences || {
                localPeerSdpConstraints: {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: isData(connection.session)
            });
            return;
        }

        if (message.message.readyForOffer || message.message.addMeAsBroadcaster) {
            connection.addNewBroadcaster(message.sender);
        }

        if (message.message.newParticipationRequest && message.sender !== connection.userid) {
            if (connection.peers[message.sender]) {
                connection.deletePeer(message.sender);
            }

            var userPreferences = {
                extra: message.message.extra || {},
                localPeerSdpConstraints: message.message.remotePeerSdpConstraints || {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: message.message.localPeerSdpConstraints || {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: typeof message.message.isDataOnly !== 'undefined' ? message.message.isDataOnly : isData(connection.session),
                dontGetRemoteStream: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                dontAttachLocalStream: !!message.message.dontGetRemoteStream,
                connectionDescription: message,
                successCallback: function() {
                    // if its oneway----- todo: THIS SEEMS NOT IMPORTANT.
                    if (typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way') {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }

                    if (!!connection.session.oneway || connection.direction === 'one-way' || isData(connection.session)) {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }
                }
            };

            connection.onNewParticipant(message.sender, userPreferences);
            return;
        }

        if (message.message.shiftedModerationControl) {
            connection.onShiftedModerationControl(message.sender, message.message.broadcasters);
            return;
        }

        if (message.message.changedUUID) {
            if (connection.peers[message.message.oldUUID]) {
                connection.peers[message.message.newUUID] = connection.peers[message.message.oldUUID];
                delete connection.peers[message.message.oldUUID];
            }
        }

        if (message.message.userLeft) {
            mPeer.onUserLeft(message.sender);

            if (!!message.message.autoCloseEntireSession) {
                connection.leave();
            }

            return;
        }

        mPeer.addNegotiatedMessage(message.message, message.sender);
    }

    window.addEventListener('beforeunload', function() {
        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: false
        });
    }, false);
}
1192189
public void setPeer(SocketAddress address) {
		this.remotePeer = address;
		boolean connectImmediately = false;
		if (rtpChannel != null) {
			if (rtpChannel.isConnected())
				try {
					rtpChannel.disconnect();
				} catch (IOException e) {
					logger.error(e);
				}

			connectImmediately = udpManager
					.connectImmediately((InetSocketAddress) address);
			if (connectImmediately)
				try {
					rtpChannel.connect(address);
				} catch (IOException e) {
					logger.info("Can not connect to remote address , please check that you are not using local address - 127.0.0.X to connect to remote");
					logger.error(e);
				}
		}

		if (udpManager.getRtpTimeout() > 0 && !connectImmediately) {
			if (shouldReceive) {
				lastPacketReceived = scheduler.getClock().getTime();
				scheduler.submitHeatbeat(heartBeat);
			} else {
				heartBeat.cancel();
			}
		}
	}
1126754
function(conn) {

        this._connection = conn;

        /*
        Function used to setup plugin.
        */

        /* extend name space
        *  NS.PUBSUB - XMPP Publish Subscribe namespace
        *              from XEP 60.
        *
        *  NS.PUBSUB_SUBSCRIBE_OPTIONS - XMPP pubsub
        *                                options namespace from XEP 60.
        */
        Strophe.addNamespace('PUBSUB',"http://jabber.org/protocol/pubsub");
        Strophe.addNamespace('PUBSUB_SUBSCRIBE_OPTIONS',
                             Strophe.NS.PUBSUB+"#subscribe_options");
        Strophe.addNamespace('PUBSUB_ERRORS',Strophe.NS.PUBSUB+"#errors");
        Strophe.addNamespace('PUBSUB_EVENT',Strophe.NS.PUBSUB+"#event");
        Strophe.addNamespace('PUBSUB_OWNER',Strophe.NS.PUBSUB+"#owner");
        Strophe.addNamespace('PUBSUB_AUTO_CREATE',
                             Strophe.NS.PUBSUB+"#auto-create");
        Strophe.addNamespace('PUBSUB_PUBLISH_OPTIONS',
                             Strophe.NS.PUBSUB+"#publish-options");
        Strophe.addNamespace('PUBSUB_NODE_CONFIG',
                             Strophe.NS.PUBSUB+"#node_config");
        Strophe.addNamespace('PUBSUB_CREATE_AND_CONFIGURE',
                             Strophe.NS.PUBSUB+"#create-and-configure");
        Strophe.addNamespace('PUBSUB_SUBSCRIBE_AUTHORIZATION',
                             Strophe.NS.PUBSUB+"#subscribe_authorization");
        Strophe.addNamespace('PUBSUB_GET_PENDING',
                             Strophe.NS.PUBSUB+"#get-pending");
        Strophe.addNamespace('PUBSUB_MANAGE_SUBSCRIPTIONS',
                             Strophe.NS.PUBSUB+"#manage-subscriptions");
        Strophe.addNamespace('PUBSUB_META_DATA',
                             Strophe.NS.PUBSUB+"#meta-data");
        Strophe.addNamespace('ATOM', "http://www.w3.org/2005/Atom");

        if (conn.disco)
            conn.disco.addFeature(Strophe.NS.PUBSUB);

    }
1008243
function(recievedPeerId) {
        if (!isDeviceRegister) {
          if (registerDeviceTimeoutId) {
            clearTimeout(registerDeviceTimeoutId);
          }

          isDeviceRegister = true;
          peerId = recievedPeerId;
        }

        /**
         * If serverRegisteration == true we have to register
         * on server then make async status ready
         */
        if (serverRegisteration) {
          if (isServerRegister && peerId === oldPeerId) {
            fireEvent("asyncReady");
            isServerRegister = true;
            pushSendDataQueueHandler();

            socketState = socketStateType.OPEN;
            fireEvent("stateChange", {
              socketState: socketState,
              timeUntilReconnect: 0,
              deviceRegister: isDeviceRegister,
              serverRegister: isServerRegister,
              peerId: peerId
            });
          } else {
            socketState = socketStateType.OPEN;
            fireEvent("stateChange", {
              socketState: socketState,
              timeUntilReconnect: 0,
              deviceRegister: isDeviceRegister,
              serverRegister: isServerRegister,
              peerId: peerId
            });

            registerServer();
          }
        } else {
          fireEvent("asyncReady");
          isServerRegister = "Not Needed";
          pushSendDataQueueHandler();

          if (asyncLogging) {
            if (workerId > 0) {
              Utility.asyncStepLogger(workerId + "\t Async is Ready");
            } else {
              Utility.asyncStepLogger("Async is Ready");
            }
          }

          socketState = socketStateType.OPEN;
          fireEvent("stateChange", {
            socketState: socketState,
            timeUntilReconnect: 0,
            deviceRegister: isDeviceRegister,
            serverRegister: isServerRegister,
            peerId: peerId
          });
        }
      }
1097808
private static void completeConnection(IoSession session, RTMPMinaConnection conn, RTMP rtmp, OutboundHandshake handshake) {
        if (handshake.useEncryption()) {
            // set encryption flag the rtmp state
            rtmp.setEncrypted(true);
            // add the ciphers
            log.debug("Adding ciphers to the session");
            session.setAttribute(RTMPConnection.RTMPE_CIPHER_IN, handshake.getCipherIn());
            session.setAttribute(RTMPConnection.RTMPE_CIPHER_OUT, handshake.getCipherOut());
        }
        // set state to indicate we're connected
        conn.getState().setState(RTMP.STATE_CONNECTED);
        log.debug("Connected, removing handshake data");
        // remove handshake from session now that we are connected
        session.removeAttribute(RTMPConnection.RTMP_HANDSHAKE);
        // add protocol filter as the last one in the chain
        log.debug("Adding RTMP protocol filter");
        session.getFilterChain().addAfter("rtmpeFilter", "protocolFilter", new ProtocolCodecFilter(new RTMPMinaCodecFactory()));
        // get the rtmp handler
        BaseRTMPClientHandler handler = (BaseRTMPClientHandler) session.getAttribute(RTMPConnection.RTMP_HANDLER);
        handler.connectionOpened(conn);
    }
221287
function peerResolved (ip, addressType) {
    // Possible cancelation during DNS lookup.
    if (!socket._connecting) return;

    socket._peer = { address: ip || '127.0.0.1', port: options.port };

    // Generate random bytes used to set randomized socket properties.
    // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes.
    //
    //  * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html).
    //  * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517)
    crypto.randomBytes(4, valid(randomzied));
  }
912283
private void enableClipPathSupportIfNecessary() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (rippleRoundedCorners != 0) {
                layerType = getLayerType();
                setLayerType(LAYER_TYPE_SOFTWARE, null);
            } else {
                setLayerType(layerType, null);
            }
        }
    }
396221
def AddConnectedPeer(self, peer):
        
        # if present
        self.RemoveFromQueue(peer.address)
        self.AddKnownAddress(peer.address)

        if len(self.Peers) > settings.CONNECTED_PEER_MAX:
            peer.Disconnect("Max connected peers reached", isDead=False)

        if peer not in self.Peers:
            self.Peers.append(peer)
        else:
            # either peer is already in the list and it has reconnected before it timed out on our side
            # or it's trying to connect multiple times
            # or we hit the max connected peer count
            self.RemoveKnownAddress(peer.address)
            peer.Disconnect()
1262948
function WebRTCSession(params) {
    this.ID = params.sessionID ? params.sessionID : generateUUID();
    this.state = WebRTCSession.State.NEW;

    this.initiatorID = parseInt(params.initiatorID);
    this.opponentsIDs = params.opIDs;
    this.callType = parseInt(params.callType);

    this.peerConnections = {};

    this.localStream = null;

    this.mediaParams = null;

    this.signalingProvider = params.signalingProvider;

    this.currentUserID = params.currentUserID;

    this.bandwidth = params.bandwidth;

    /**
     * We use this timeout to fix next issue:
     * "From Android/iOS make a call to Web and kill the Android/iOS app instantly. Web accept/reject popup will be still visible.
     * We need a way to hide it if sach situation happened."
     */
    this.answerTimer = null;

    this.startCallTime = 0;
    this.acceptCallTime = 0;
}
940097
function TcpStreamConnect () {
        this.simulator.Debug (3, 'Dispatcher connected to %s:%s', simulator.opts.host, simulator.opts.port);
        ActiveClients[this] = this;  // register on remote server in active socket list
    }
338758
def openRtpPort(self):
    """"""
    #-------------
    # TO COMPLETE
    #-------------
    # Create a new datagram socket to receive RTP packets from the server
    # self.rtpSocket = ...


    # Set the timeout value of the socket to 0.5sec
    # ...
    self.rtpSocket.settimeout(0.5)
#   try:
      # Bind the socket to the address using the RTP port given by the client user
      # ...
#   except:
#     tkMessageBox.showwarning('Unable to Bind', 'Unable to bind PORT=%d' %self.rtpPort)

    try:
      #self.rtpSocket.connect(self.serverAddr,self.rtpPort)
      self.rtpSocket.bind((self.serverAddr,self.rtpPort))   # WATCH OUT THE ADDRESS FORMAT!!!!!  rtpPort# should be bigger than 1024
      #self.rtpSocket.listen(5)
      print("Bind RtpPort Success")

    except:
      tkinter.messagebox.showwarning('Connection Failed', 'Connection to rtpServer failed...')