Connects to sshd on host:port
Retries while attempts reached with delay
First with tcp port wait, then with ssh connection wait

@throws IOException if no retries left
968411
public void bySshWithEveryRetryWaitFor(int time, TimeUnit units) throws IOException {
        checkState(withEveryRetryWaitFor(time, units), "Port %s is not opened to connect to", hostAndPort.getPort());

        for (int i = 1; i <= retries; i++) {
            Connection connection = new Connection(hostAndPort.getHostText(), hostAndPort.getPort());
            try {
                connection.connect(null, 0, sshTimeoutMillis, sshTimeoutMillis);
                LOG.info("SSH port is open on {}:{}", hostAndPort.getHostText(), hostAndPort.getPort());
                return;
            } catch (IOException e) {
                LOG.error("Failed to connect to {}:{} (try {}/{}) - {}",
                        hostAndPort.getHostText(), hostAndPort.getPort(), i, retries, e.getMessage());
                if (i == retries) {
                    throw e;
                }
            } finally {
                connection.close();
            }
            sleepFor(time, units);
        }
    }
886258
def connect(self, host, port, name=None):
        
        client = self._clients.get(name)
        client.connect_to(host, port)
810721
private void connect(String host, int port) throws SQLException, IOException {
    try {
      socket = Utils.createSocket(urlParser, host);
      if (options.socketTimeout != null) {
        socket.setSoTimeout(options.socketTimeout);
      }

      initializeSocketOption();

      // Bind the socket to a particular interface if the connection property
      // localSocketAddress has been defined.
      if (options.localSocketAddress != null) {
        InetSocketAddress localAddress = new InetSocketAddress(options.localSocketAddress, 0);
        socket.bind(localAddress);
      }

      if (!socket.isConnected()) {
        InetSocketAddress sockAddr =
            urlParser.getOptions().pipe == null ? new InetSocketAddress(host, port) : null;
        if (options.connectTimeout != 0) {
          socket.connect(sockAddr, options.connectTimeout);
        } else {
          socket.connect(sockAddr);
        }
      }

      handleConnectionPhases(host);

      connected = true;

      if (options.useCompression) {
        writer = new CompressPacketOutputStream(writer.getOutputStream(),
            options.maxQuerySizeToLog);
        reader = new DecompressPacketInputStream(
            ((StandardPacketInputStream) reader).getInputStream(),
            options.maxQuerySizeToLog);
        if (options.enablePacketDebug) {
          writer.setTraceCache(traceCache);
          reader.setTraceCache(traceCache);
        }
      }

      boolean mustLoadAdditionalInfo = true;
      if (globalInfo != null) {
        if (globalInfo.isAutocommit() == options.autocommit) {
          mustLoadAdditionalInfo = false;
        }
      }

      if (mustLoadAdditionalInfo) {
        Map<String, String> serverData = new TreeMap<>();
        if (options.usePipelineAuth && !options.createDatabaseIfNotExist) {
          try {
            sendPipelineAdditionalData();
            readPipelineAdditionalData(serverData);
          } catch (SQLException sqle) {
            if ("08".equals(sqle.getSQLState())) {
              throw sqle;
            }
            //in case pipeline is not supported
            //(proxy flush socket after reading first packet)
            additionalData(serverData);
          }
        } else {
          additionalData(serverData);
        }

        writer.setMaxAllowedPacket(Integer.parseInt(serverData.get("max_allowed_packet")));
        autoIncrementIncrement = Integer.parseInt(serverData.get("auto_increment_increment"));
        loadCalendar(serverData.get("time_zone"), serverData.get("system_time_zone"));

      } else {

        writer.setMaxAllowedPacket((int) globalInfo.getMaxAllowedPacket());
        autoIncrementIncrement = globalInfo.getAutoIncrementIncrement();
        loadCalendar(globalInfo.getTimeZone(), globalInfo.getSystemTimeZone());
      }

      reader.setServerThreadId(this.serverThreadId, isMasterConnection());
      writer.setServerThreadId(this.serverThreadId, isMasterConnection());

      activeStreamingResult = null;
      hostFailed = false;
    } catch (IOException | SQLException ioException) {
      ensureClosingSocketOnException();
      throw ioException;
    }
  }
1221285
private void initSocket()
    throws IOException
  {
    _idleTimeout = _port.getKeepaliveTimeout();

    _port.ssl(_socket);

    writeStream().init(_socket.stream());

    // ReadStream cannot use getWriteStream or auto-flush
    // because of duplex mode
    // ReadStream is = getReadStream();
    _readStream.init(_socket.stream());

    if (log.isLoggable(Level.FINEST)) {
      log.finest(dbgId() + "starting connection " + this
                 + ", total=" + _port.getConnectionCount());
    }
  }
1107199
public void connect() throws IOException {
        SmbTransport trans;
        SmbSession ssn;
        UniAddress addr;

        if( isConnected() ) {
            return;
        }

        getUncPath0();
        getFirstAddress();
        for ( ;; ) {
            try {
                doConnect();
                return;
            } catch(SmbAuthException sae) {
                throw sae; // Prevents account lockout on servers with multiple IPs
            } catch(SmbException se) {
                if (getNextAddress() == null) 
                    throw se;
                if (log.level >= 3)
                    se.printStackTrace(log);
            }
        }
    }
80728
def connect(self, (host, port)):
        '''
        
        '''
        self._host = "%s:%s" % (host, port)
        self._sock = EventSocket(
            read_cb=self._sock_read_cb,
            close_cb=self._sock_close_cb,
            error_cb=self._sock_error_cb,
            debug=self.connection.debug,
            logger=self.connection.logger)
        if self.connection._sock_opts:
            for k, v in self.connection._sock_opts.iteritems():
                family, type = k
                self._sock.setsockopt(family, type, v)
        self._sock.setblocking(False)
        self._sock.connect(
            (host, port), timeout=self.connection._connect_timeout)
        self._heartbeat_timeout = None
943873
public void connect (int timeout, String host, int tcpPort) throws IOException {
		connect(timeout, InetAddress.getByName(host), tcpPort, -1);
	}
591446
private SshConnection connect() {
        if (sshConnection != null && sshConnection.isConnected()) {
            return sshConnection;
        }
        while (!shutdownInProgress) {
            SshConnection ssh = null;
            try {
                logger.debug("Connecting...");
                ssh = SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
                        authentication, authenticationUpdater);
                gerritVersion  = formatVersion(ssh.executeCommand("gerrit version"));
                logger.debug("connection seems ok, returning it.");
                return ssh;
            } catch (SshConnectException sshConEx) {
                logger.error("Could not connect to Gerrit server! "
                        + "Host: {} Port: {}", gerritHostName, gerritSshPort);
                logger.error(" Proxy: {}", gerritProxy);
                logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
                logger.error("ConnectionException: ", sshConEx);
            } catch (SshAuthenticationException sshAuthEx) {
                logger.error("Could not authenticate to Gerrit server!"
                        + "\n\tUsername: {}\n\tKeyFile: {}\n\tPassword: {}",
                        new Object[]{authentication.getUsername(),
                                authentication.getPrivateKeyFile(),
                                authentication.getPrivateKeyFilePassword(), });
                logger.error("AuthenticationException: ", sshAuthEx);
            } catch (IOException ex) {
                logger.error("Could not connect to Gerrit server! "
                        + "Host: {} Port: {}", gerritHostName, gerritSshPort);
                logger.error(" Proxy: {}", gerritProxy);
                logger.error(" User: {} KeyFile: {}", authentication.getUsername(), authentication.getPrivateKeyFile());
                logger.error("IOException: ", ex);
            }

            if (ssh != null) {
                logger.trace("Disconnecting bad connection.");
                try {
                    //The ssh lib used is starting at least one thread for each connection.
                    //The thread isn't shutdown properly when the connection goes down,
                    //so we need to close it "manually"
                    ssh.disconnect();
                } catch (Exception ex) {
                    logger.warn("Error when disconnecting bad connection.", ex);
                } finally {
                    ssh = null;
                }
            }

            if (!shutdownInProgress) {
                //If we end up here, sleep for a while and then go back up in the loop.
                logger.trace("Sleeping for a bit.");
                try {
                    Thread.sleep(CONNECT_SLEEP);
                } catch (InterruptedException ex) {
                    logger.warn("Got interrupted while sleeping.", ex);
                }
            }
        }
        return null;
    }
1254895
async def _connect(self, hostname, port, reconnect=False, password=None, encoding=pydle.protocol.DEFAULT_ENCODING, channels=[], tls=False, tls_verify=False, source_address=None):
        
        self.password = password

        # Create connection if we can't reuse it.
        if not reconnect:
            self._autojoin_channels = channels
            self.connection = connection.Connection(hostname, port,
                source_address=source_address,
                tls=tls, tls_verify=tls_verify,
                tls_certificate_file=self.tls_client_cert,
                tls_certificate_keyfile=self.tls_client_cert_key,
                tls_certificate_password=self.tls_client_cert_password,
                eventloop=self.eventloop)
            self.encoding = encoding

        # Connect.
        await self.connection.connect()
1334777
private void init(int port, File commandFileTmp) throws IOException {
        if (port != -1) {
            serverSocketChannel = SelectorProvider.provider().openServerSocketChannel();

            // Open the socket for loopback only..
            InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(null), port);

            IOException bindError = null;

            boolean isWindows = System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows");

            try {
                //Attempt bind with reuseAddress set to false.
                serverSocketChannel.socket().setReuseAddress(false);
                serverSocketChannel.socket().bind(address);

                //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                //for future binds.
                if (!isWindows) {
                    serverSocketChannel.socket().setReuseAddress(true);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                    }
                }
            } catch (IOException ioe) {
                // see if we got the error because port is in waiting to be cleaned up.
                // If so, no one should be accepting connections on it, and open should fail.
                // If that's the case, we can set ReuseAddr to expedite the bind process.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                }
                bindError = ioe;
                try {
                    InetSocketAddress testAddr = new InetSocketAddress(InetAddress.getByName(null), port);
                    if (!testAddr.isUnresolved()) {
                        SocketChannel testChannel = SocketChannel.open(testAddr);
                        // if we get here, socket opened successfully, which means someone is really listening
                        // so close connection and don't bother trying to bind again
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "attempt to connect to command port to check listen status worked, someone else is using the port!");
                        }
                        testChannel.close();
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                        }
                    }
                } catch (IOException testioe) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "attempt to connect to command port to check listen status failed with IOException: " + testioe.getMessage());
                    }
                    try {
                        // open (or close) got IOException, retry with reuseAddress set to true
                        serverSocketChannel.socket().setReuseAddress(true);
                        serverSocketChannel.socket().bind(address);
                        bindError = null;

                    } catch (IOException newioe) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                        }
                        bindError = newioe;
                    }
                }
            }

            if (bindError == null) {
                // if we requested an ephemeral port, find out what port we ended up with
                if (port == 0) {
                    port = serverSocketChannel.socket().getLocalPort();
                }
                listenForCommands = true;
            } else {
                throw bindError;
            }
        }

        ServerCommandID sci = new ServerCommandID(port, serverUUID);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(commandFileTmp);
            fos.write(sci.getIDString().getBytes());
            fos.close();
        } finally {
            Utils.tryToClose(fos);
        }
    }
194716
def await_connection(host, port):
    """"""
    for i in range(CONNECT_ATTEMPTS):
        try:
            conn = socket.create_connection((host, port), CONNECT_TIMEOUT)
            conn.close()
            return True
        except (IOError, socket.error):
            time.sleep(1)
    return False
362146
public void connect() throws IOException, DeploymentException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(this, wssUri);
        log.debug("client connected to the server: {}", wssUri);
    }
511831
protected SshConnection getConnection() throws IOException {
        return SshConnectionFactory.getConnection(gerritHostName, gerritSshPort, gerritProxy,
                authentication, connectionTimeout);
    }
719053
def _try_connect(self, host):
        
        log.debug("[control connection] Opening new connection to %s", host)

        while True:
            try:
                connection = self._cluster.connection_factory(host.endpoint, is_control_connection=True)
                if self._is_shutdown:
                    connection.close()
                    raise DriverException("Reconnecting during shutdown")
                break
            except ProtocolVersionUnsupported as e:
                self._cluster.protocol_downgrade(host.endpoint, e.startup_version)

        log.debug("[control connection] Established new connection %r, "
                  "registering watchers and refreshing schema and topology",
                  connection)

        # use weak references in both directions
        # _clear_watcher will be called when this ControlConnection is about to be finalized
        # _watch_callback will get the actual callback from the Connection and relay it to
        # this object (after a dereferencing a weakref)
        self_weakref = weakref.ref(self, partial(_clear_watcher, weakref.proxy(connection)))
        try:
            connection.register_watchers({
                "TOPOLOGY_CHANGE": partial(_watch_callback, self_weakref, '_handle_topology_change'),
                "STATUS_CHANGE": partial(_watch_callback, self_weakref, '_handle_status_change'),
                "SCHEMA_CHANGE": partial(_watch_callback, self_weakref, '_handle_schema_change')
            }, register_timeout=self._timeout)

            sel_peers = self._SELECT_PEERS if self._token_meta_enabled else self._SELECT_PEERS_NO_TOKENS
            sel_local = self._SELECT_LOCAL if self._token_meta_enabled else self._SELECT_LOCAL_NO_TOKENS
            peers_query = QueryMessage(query=sel_peers, consistency_level=ConsistencyLevel.ONE)
            local_query = QueryMessage(query=sel_local, consistency_level=ConsistencyLevel.ONE)
            shared_results = connection.wait_for_responses(
                peers_query, local_query, timeout=self._timeout)

            self._refresh_node_list_and_token_map(connection, preloaded_results=shared_results)
            self._refresh_schema(connection, preloaded_results=shared_results, schema_agreement_wait=-1)
        except Exception:
            connection.close()
            raise

        return connection
460640
async def _connect(self, hostname, port, reconnect=False, channels=[],
                       encoding=protocol.DEFAULT_ENCODING, source_address=None):
        
        # Create connection if we can't reuse it.
        if not reconnect or not self.connection:
            self._autojoin_channels = channels
            self.connection = connection.Connection(hostname, port, source_address=source_address,
                                                    eventloop=self.eventloop)
            self.encoding = encoding

        # Connect.
        await self.connection.connect()
300500
@Override
	public void open(Configuration parameters) throws Exception {
		try {
			synchronized (lock) {
				createConnection();
			}
		}
		catch (IOException e) {
			throw new IOException("Cannot connect to socket server at " + hostName + ":" + port, e);
		}
	}
170350
public String connectAndBind(String host, int port,
            BindParameter bindParam) 
            throws IOException {
        return connectAndBind(host, port, bindParam, 60000);
    }