This function is called by passive simultaneous nodes who
        wish to establish themself as such. It sets up a connection
        to the Rendezvous Server to monitor for new hole punching requests.
185561
def simultaneous_listen(self):
        

        # Close socket.
        if self.server_con is not None:
            self.server_con.s.close()
            self.server_con = None

        # Reset predictions + mappings.
        self.mappings = None
        self.predictions = None

        # Connect to rendezvous server.
        parts = self.sequential_connect()
        if parts is None:
            return 0
        con, mappings, predictions = parts
        con.blocking = 0
        con.timeout = 0
        con.s.settimeout(0)
        self.server_con = con
        self.mappings = mappings
        self.predictions = predictions

        # Register simultaneous node with server.
        msg = "SIMULTANEOUS READY 0 0"
        ret = self.server_con.send_line(msg)
        if not ret:
            return 0
        return 1
901478
function addConnection(conn) {

  this.emit('connect');

  function onInput(len) {
    this._stats.ibytes += len;
  }

  function onOutput(len) {
    this._stats.obytes += len;
  }

  conn.on('input', onInput.bind(this));
  conn.on('output', onOutput.bind(this));

  this._conn.push(conn);

  // pubsub needs to know the client index
  // to be able to quickly find client subscribers
  conn.client.index = this._conn.length - 1;
}
59970
public static BiFunction<WebsocketInbound, WebsocketOutbound, Publisher<Void>> newHandler(
      ConnectionAcceptor acceptor, int mtu) {
    return (in, out) -> {
      DuplexConnection connection = new WebsocketDuplexConnection((Connection) in);
      if (mtu > 0) {
        connection =
            new FragmentationDuplexConnection(
                connection, ByteBufAllocator.DEFAULT, mtu, false, "server");
      }
      return acceptor.apply(connection).then(out.neverComplete());
    };
  }
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()
881666
function setup(connection) {

                var request = undefined;
                var reply_to = undefined;
                var response = undefined;

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                node.sender = node.connection.open_sender({ target: {} });

                // build receiver options
                var receiver_options = {
                    source: {
                        address: node.address
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {

                    // save request and reply_to address on AMQP message received
                    request = context.message;
                    reply_to = request.reply_to;

                    // provides the request and delivery as node output
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (reply_to) {

                            // fill the response with the provided one as input
                            response = msg.payload;
                            response.to = reply_to;

                            node.sender.send(response);
                        }
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })

            }
716991
protected synchronized void connectionPending()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "connectionPending");
        ++connectAttemptsPending;
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(this, tc, connectAttemptsPending + " connection attempts now pending");
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "connectionPending");
    }
1249244
void establishConnection () throws IOException {
        synchronized (operationOnConnectionMonitor) {
            if (state == State.CLOSED) {
                throw new IOException("Attempt to establish a connection with a closed connection factory");
            } else if (state == State.CONNECTED) {
                LOGGER.warn("Establishing new connection although a connection is already established");
            }
            try {
                LOGGER.info("Trying to establish connection to {}:{}", getHost(), getPort());
                connection = super.newConnection(executorService);
                connection.addShutdownListener(connectionShutdownListener);
                LOGGER.info("Established connection to {}:{}", getHost(), getPort());
                changeState(State.CONNECTED);
            } catch (IOException e) {
                LOGGER.error("Failed to establish connection to {}:{}", getHost(), getPort());
                throw e;
            }
        }
    }
1004131
def _maybe_connect(self, node_id):
        """"""
        with self._lock:
            conn = self._conns.get(node_id)

            if conn is None:
                broker = self.cluster.broker_metadata(node_id)
                assert broker, 'Broker id %s not in current metadata' % (node_id,)

                log.debug("Initiating connection to node %s at %s:%s",
                          node_id, broker.host, broker.port)
                host, port, afi = get_ip_port_afi(broker.host)
                cb = WeakMethod(self._conn_state_change)
                conn = BrokerConnection(host, broker.port, afi,
                                        state_change_callback=cb,
                                        node_id=node_id,
                                        **self.config)
                self._conns[node_id] = conn

            # Check if existing connection should be recreated because host/port changed
            elif self._should_recycle_connection(conn):
                self._conns.pop(node_id)
                return False

            elif conn.connected():
                return True

            conn.connect()
            return conn.connected()
124634
def throw_punch(self, args, tries=1):
        

        # Parse arguments.
        if len(args) != 3:
            return 0
        sock, node_ip, remote_port = args
        if sock is None or node_ip is None or remote_port is None:
            return 0

        # Generous timeout.
        con = Sock(blocking=1, interface=self.interface)
        con.set_sock(sock)
        local = 0
        if is_ip_private(node_ip):
            """
            When simulating nodes on the same computer a delay needs to be set
            for the loop back interface to simulate the delays that occur over
            a WAN link. This requirement may also be needed for nodes on a LAN.

            sudo tc qdisc replace dev lo root handle 1:0 netem delay 0.5sec

            Speculation: The simulation problem may be to do with CPU cores.
            If the program is run on the same core then the connects will always
            be out of sync. If that's the case -- tries will need to be set to
            ~1000 which was what it was before. Perhaps a delay could be
            simulated by sleeping for random periods if its a local connection?
            That could help punch through at least once and then just set the
            tries to >= 1000.
            """
            tries = 20  # 20
            local = 1

        source_port = sock.getsockname()[1]
        error = 0
        log.debug("Throwing punch")
        for i in range(0, tries):
            # Attempt to connect.
            try:
                con.connect(node_ip, remote_port)
                log.debug("Sim open success!")

                # FATALITY.

                # Atomic operation so mutex not required.
                # Record hole made.
                con.set_blocking(blocking=0, timeout=5)
                self.simultaneous_cons.append(con)
                return 1
            except Exception as e:
                # Punch was blocked, opponent is strong.
                e = str(parse_exception(e))
                log.debug(e)
                error = 1
                continue

        if error:
            sock.close()

        return 0
1211461
public void sendStopNodeNotice(int targetHostId) {
        // First add a notice to local
        addStopNodeNotice(targetHostId);

        // Then contact other peers
        List<FutureTask<Void>> tasks = new ArrayList<FutureTask<Void>>();
        for (int hostId : m_foreignHosts.keySet()) {
            if (hostId == m_localHostId) {
                continue; /* skip target host */
            }
            Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator();
            if (it.hasNext()) {
                ForeignHost fh = it.next();
                if (fh.isUp()) {
                    FutureTask<Void> task = fh.sendStopNodeNotice(targetHostId);
                    if (task != null) {
                        tasks.add(task);
                    }
                }
            }
        }
        for (FutureTask<Void> task : tasks) {
            try {
                task.get();
            } catch (InterruptedException | ExecutionException e) {
                hostLog.info("Failed to send StopNode notice to other nodes.");
            }
        }
    }
69838
def __start_connection(self, context, node, ccallbacks=None):
        """"""

        _logger.debug("Creating connection object: CONTEXT=[%s] NODE=[%s]", 
                      context, node)

        c = nsq.connection.Connection(
                context,
                node, 
                self.__identify, 
                self.__message_handler,
                self.__quit_ev,
                ccallbacks,
                ignore_quit=self.__connection_ignore_quit)

        g = gevent.spawn(c.run)

        # Now, wait for the thread to finish the connection.

        timeout_s = nsq.config.client.NEW_CONNECTION_NEGOTIATE_TIMEOUT_S
        if c.connected_ev.wait(timeout_s) is False:
            _logger.error("New connection to server [%s] timed-out. Cleaning-"
                          "up thread.", node)

            g.kill()
            g.join()

            # We'll try again on the next audit.

            raise EnvironmentError("Connection to server [%s] failed." % 
                                   (node,))

        self.__connections.append((node, c, g))
270051
function controlChannelRequest(server, message) {
  var address = message.request.address;
  var req = { headers: {} };
  var headers = [];

  // handler to call when the connection sequence completes
  var self = server;
  
  if ( message.request.method) {
    req = new IncomingMessage(message, server.controlChannel);
    if ( message.request.body == true) {
       self.pendingRequest = req;
    } else {
      req.push(null);
    }
  }
  
  // execute the web socket rendezvous with the server
  try {
    var client = new WebSocket(address, {
      headers: headers,
      perMessageDeflate: false
    });
    client.on('open', function() {
      
      server.emit('requestchannel', client);
      if (self.options.clientTracking) {
        self.clients.push(client);
        ws.on('close', function() {
          var index = self.clients.indexOf(client);
          if (index != -1) {
            self.clients.splice(index, 1);
          }
        });
      }

      // do we have a request or is this just rendezvous?
      if ( message.request.method) {
         var res = new ServerResponse(req);
         res.requestId = message.request.id;
         res.assignSocket(client);
         server.emit('request', req, res);
      }
    });

    client.on('error', function(event) {
      var index = server.clients.indexOf(client);
      if (index != -1) {
        server.clients.splice(index, 1);
      }
    });

  } catch (err) {
    console.log(err);
  }
}
293656
function executeReconnect(self) {
    return function() {
      if (self.state === DESTROYED || self.state === UNREFERENCED) {
        return;
      }

      connectNewServers(self, self.s.replicaSetState.unknownServers, function() {
        var monitoringFrequencey = self.s.replicaSetState.hasPrimary()
          ? _haInterval
          : self.s.minHeartbeatFrequencyMS;

        // Create a timeout
        self.intervalIds.push(new Timeout(executeReconnect(self), monitoringFrequencey).start());
      });
    };
  }
1026012
function setup(connection) {

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                // build receiver options based on node configuration
                var options = {
                    source: {
                        address: node.address,
                        dynamic: node.dynamic,
                        durable: node.durable,
                        expiry_policy: node.expirypolicy
                     },
                    credit_window: node.creditwindow,
                    autoaccept: node.autoaccept,
                    snd_settle_mode: node.sndsettlemode,
                    rcv_settle_mode: node.rcvsettlemode
                };

                node.receiver = node.connection.open_receiver(options);

                node.receiver.on('message', function(context) {
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    if (msg.credit) {
                        node.receiver.flow(msg.credit);
                    }
                });

                node.on('close', function() {
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                });
            }
503739
public synchronized void passiveConnect(DataSink sink,
                                            TransferContext context,
                                            int connections,
                                            ServerSocket serverSocket)
        throws ServerException {

        // things would get messed up if more than 1 file was transfered
        // simultaneously with the same transfer manager
        if (transferThreadCount != 0) {
            throw new ServerException(
                            ServerException.PREVIOUS_TRANSFER_ACTIVE);
        }

        for (int i = 0; i < connections; i++) {
            Task task =
                new GridFTPPassiveConnectTask(
                                serverSocket,
                                sink,
                                localControlChannel,
                                gSession,
                                dataChannelFactory,
                                (EBlockParallelTransferContext) context);

            runTask(task);
        }
    }
184751
def connect_partial_nodirect(self, config):
        
        assert 0 <= config.connection_fraction <= 1
        all_connections = self.compute_full_connections(config, False)
        shuffle(all_connections)
        num_to_add = int(round(len(all_connections) * config.connection_fraction))
        for input_id, output_id in all_connections[:num_to_add]:
            connection = self.create_connection(config, input_id, output_id)
            self.connections[connection.key] = connection
19617
def maybe_connect(self, node_id, wakeup=True):
        """"""
        if self._can_connect(node_id):
            self._connecting.add(node_id)
            # Wakeup signal is useful in case another thread is
            # blocked waiting for incoming network traffic while holding
            # the client lock in poll().
            if wakeup:
                self.wakeup()
            return True
        return False