invoked when peer connection, notifies server and resends offser if stream is enabled
483722
function onPeerConnected(peer)
    {
        if(scope.localStream)
        {
            peer.updateStream(scope.localStream,false);
        }
        scope._servConn.sendRTCState(true,peer.id);

        scope.dispatchEvent("peerConnected",peer.id);
    }
527084
private void checkEnd() {
    if (ended && !closed && children == 0) {
      closed = true;
      connection.doBatchEnd(id, endArgs);
      if (endHandler != null) {
        endHandler.handle((Void) null);
      }
    }
  }
327986
function StreamHandler(host, port, delimiter) {
	events.EventEmitter.call(this);

	var self = this;
	self.delimiter = delimiter || "\r\n";
	self.host      = host;
	self.port      = port;

	self.buffer    = '';

	self.conn = net.createConnection(self.port, self.host);
	self.conn.setEncoding("utf8");

	self.conn.on('error', function(err) {
		try {
			self.emit('error', 'Stream error: ' + err, err);
		} catch (e) {
			console.log('' + err);
		}
	});
	self.conn.on('data', function(data) {
		self.conn.pause();
		self.buffer += data;
		if (self.buffer.match(/\n/)) {
			var arr = self.buffer.split(self.delimiter);
			//Everything except the last one
			for(var i = 0; i < arr.length - 1; i++) {
				self.emit('line', arr[i]);
			}
			self.buffer = arr[arr.length - 1];
		}
		if (self.conn.readyState == 'open') {
			self.conn.resume();
		}
	});
	self.conn.on('close', function(had_error) {
		if (!had_error && self.buffer.length > 0) {
			self.emit('line', self.buffer);
		}
	});
}
309581
public void flush()
    {
        //  The peer does not exist anymore at this point.
        if (state == State.TERM_ACK_SENT) {
            return;
        }

        if (outpipe != null && !outpipe.flush()) {
            sendActivateRead(peer);
        }
    }
1363
protected function onRead()
    {
        start:
        if ($this->getInputLength() < 5) {
            return;
        }
        /* @TODO: refactoring Binary::* to support direct buffer calls */
        $pct = $this->read(4096);
        $h = Binary::getDWord($pct);
        if ($h !== 0xFFFFFFFF) {
            $this->finish();
            return;
        }
        $type = Binary::getChar($pct);
        if (($type === Pool::S2A_INFO) || ($type === Pool::S2A_INFO_SOURCE)) {
            $result = self::parseInfo($pct, $type);
        } elseif ($type === Pool::S2A_PLAYER) {
            $result = self::parsePlayers($pct);
        } elseif ($type === Pool::S2A_SERVERQUERY_GETCHALLENGE) {
            $result = mb_orig_substr($pct, 0, 4);
            $pct = mb_orig_substr($pct, 5);
        } elseif ($type === Pool::S2A_PONG) {
            $result = true;
        } else {
            $result = null;
        }
        $this->onResponse->executeOne($this, $result);
        $this->checkFree();
        goto start;
    }
716072
function onPeerClose(peer)
    {
        var id = peer.id;
        scope.removePeer(peer);
        sendPeerClose(id);

        scope.dispatchEvent("peerDisconnected",id);
    }
1291724
private boolean acceptStream(
            int streamId, byte priority, boolean remoteSideClosed, boolean localSideClosed) {
        // Cannot initiate any new streams after receiving or sending GOAWAY
        if (receivedGoAwayFrame || sentGoAwayFrame) {
            return false;
        }

        boolean remote = isRemoteInitiatedId(streamId);
        int maxConcurrentStreams = remote ? localConcurrentStreams : remoteConcurrentStreams;
        if (spdySession.numActiveStreams(remote) >= maxConcurrentStreams) {
            return false;
        }
        spdySession.acceptStream(
                streamId, priority, remoteSideClosed, localSideClosed,
                initialSendWindowSize, initialReceiveWindowSize, remote);
        if (remote) {
            lastGoodStreamId = streamId;
        }
        return true;
    }
810665
public void eventHubConnect(String peerUrl, String pem) {
        this.eventHub.setPeerAddr(peerUrl, pem);
        this.eventHub.connect();
    }
1256469
private void pollUpstream() {
    if (!awaitingInner) {
      return;
    }

    boolean localDone = this.done;

    // Try to move the new item into the reframer
    InnerT newUpstreamItem = newItem.getAndSet(null);
    if (newUpstreamItem != null) {
      reframer.push(newUpstreamItem);
      // and reset the awaiting flag, if the item arrived or upstream closed
      awaitingInner = false;
    } else if (localDone) {
      awaitingInner = false;
    }
  }
140816
function onListening() {
    const addr = server.address();
    const bind = (typeof addr === 'string')
                ? 'pipe ' + addr
                : 'port ' + addr.port;
    debugServer('Listening on ' + bind);
  }
1178869
void data(boolean outFinished, int streamId, Buffer source, boolean flush) {
    Preconditions.checkNotNull(source, "source");

    OkHttpClientStream stream = transport.getStream(streamId);
    if (stream == null) {
      // This is possible for a stream that has received end-of-stream from server (but hasn't sent
      // end-of-stream), and was removed from the transport stream map.
      // In such case, we just throw away the data.
      return;
    }

    OutboundFlowState state = state(stream);
    int window = state.writableWindow();
    boolean framesAlreadyQueued = state.hasPendingData();
    int size = (int) source.size();

    if (!framesAlreadyQueued && window >= size) {
      // Window size is large enough to send entire data frame
      state.write(source, size, outFinished);
    } else {
      // send partial data
      if (!framesAlreadyQueued && window > 0) {
        state.write(source, window, false);
      }
      // Queue remaining data in the buffer
      state.enqueue(source, (int) source.size(), outFinished);
    }

    if (flush) {
      flush();
    }
  }
331058
private void notifyInactive(Peer peer) {
		for(Listener listener : new HashSet<>(listeners)) {
			listener.onInactive(peer);
		}
	}
1226406
public void start(final URI defaultTrackerURI, final AnnounceResponseListener listener, final Peer[] peers, final int announceInterval) {
    myAnnounceInterval = announceInterval;
    myPeers.addAll(Arrays.asList(peers));
    if (defaultTrackerURI != null) {
      try {
        myDefaultTracker = myTrackerClientFactory.createTrackerClient(myPeers, defaultTrackerURI);
        myDefaultTracker.register(listener);
        this.clients.put(defaultTrackerURI.toString(), myDefaultTracker);
      } catch (Exception e) {
      }
    } else {
      myDefaultTracker = null;
    }

    this.stop = false;
    this.forceStop = false;

    if (this.thread == null || !this.thread.isAlive()) {
      this.thread = new Thread(this);
      this.thread.setName("torrent tracker announce thread");
      this.thread.start();
    }
  }
792776
function isStreamReady(self) {
	const method = 'isStreamReady';
	let ready = false;
	if (self._stream) {
		const stream = self._stream;
		ready = stream.readable && stream.writable && stream.reading;
		logger.debug('%s - stream.readable %s :: %s', method, stream.readable, self.getPeerAddr());
		logger.debug('%s - stream.writable %s :: %s', method, stream.writable, self.getPeerAddr());
		logger.debug('%s - stream.reading %s :: %s', method, stream.reading, self.getPeerAddr());
		logger.debug('%s - stream.read_status %s :: %s', method, stream.read_status, self.getPeerAddr());
		logger.debug('%s - stream.received_status %s :: %s', method, stream.received_status, self.getPeerAddr());
	}

	return ready;
}
1186698
def on_update_enabled(self, conf_evt):
        
        enabled = conf_evt.value
        # If we do not have any protocol bound and configuration asks us to
        # enable this peer, we try to establish connection again.
        if enabled:
            LOG.info('%s enabled', self)
            if self._protocol and self._protocol.started:
                LOG.error('Tried to enable neighbor that is already enabled')
            else:
                self.state.bgp_state = const.BGP_FSM_CONNECT
                # Restart connect loop if not already running.
                if not self._connect_retry_event.is_set():
                    self._connect_retry_event.set()
                    LOG.debug('Starting connect loop as neighbor is enabled.')
        else:
            LOG.info('%s disabled', self)
            if self._protocol:
                # Stopping protocol will eventually trigger connection_lost
                # handler which will do some clean-up.
                # But the greenlet that is in charge of the socket may be kill
                # when we stop the protocol, hence we call connection_lost
                # here as we triggered socket to close.
                self._protocol.send_notification(
                    BGP_ERROR_CEASE,
                    BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN
                )
                self._protocol.stop()
                self._protocol = None
                self.state.bgp_state = const.BGP_FSM_IDLE
            # If this peer is not enabled any-more we stop trying to make any
            # connection.
            LOG.debug('Disabling connect-retry as neighbor was disabled')
            self._connect_retry_event.clear()
897858
function addStreamToPeerConnection(stream, peerConnection) {
       if( peerConnection.addStream ) {
           var existingStreams = peerConnection.getLocalStreams();
           if (existingStreams.indexOf(stream) === -1) {
              peerConnection.addStream(stream);
           }
       }
       else {
          var existingTracks = peerConnection.getSenders();
          var tracks = stream.getAudioTracks();
          var i;
          for( i = 0; i < tracks.length; i++ ) {
            if (existingTracks.indexOf(tracks[i]) === -1) {
             peerConnection.addTrack( tracks[i]);
            }
          }
          tracks = stream.getVideoTracks();
          for( i = 0; i < tracks.length; i++ ) {
            if (existingTracks.indexOf(tracks[i]) === -1) {
             peerConnection.addTrack( tracks[i]);
            }
          }
       }
    }
217610
async def _handle(self, reader, writer):
        
        peer = writer.get_extra_info('peername')
        self._logger.debug('New connection from {}'.format(peer))
        try:
            # Loop handling requests
            while True:
                # Read the request
                req = Request()
                await req._read(reader)

                # Find and execute handler
                res = None
                for path_regex, handler in self._handlers.get(req.method, []):
                    match = path_regex.fullmatch(req.path)
                    if match:
                        req.match = match
                        try:
                            if inspect.iscoroutinefunction(handler):
                                res = await handler(self.env, req)
                            else:
                                res = handler(self.env, req)
                            if not isinstance(res, Response):
                                res = Response(data=res)
                        except:
                            # Error - log it and return 500
                            self._logger.error(traceback.format_exc())
                            res = Response(code=500, reason='Internal Server Error')
                        break

                # No handler - send 404
                if res == None:
                    res = Response(code=404, reason='Not Found')

                # Respond
                await res._write(writer)
                self._logger.info('{}: {} -> {}'.format(peer, req.path,  res.code))
        except EOFError:
            self._logger.debug('Connection closed from {}'.format(peer))
        except Exception as e:
            self._logger.error('Connection error ({}) from {}'.format(e, peer))
            writer.close()