Connect to a single server with retry. Limited exponential backoff.
No timeout. This will run until the process is killed if it's not
able to connect.

@param server hostname:port or just hostname (hostname can be ip).
344400
static void connectToOneServerWithRetry(Client client, String server) {
        int sleep = 1000;
        while (true) {
            try {
                client.createConnection(server);
                break;
            }
            catch (Exception e) {
                System.err.printf("Connection failed - retrying in %d second(s).\n", sleep / 1000);
                try { Thread.sleep(sleep); } catch (Exception interruted) {}
                if (sleep < 8000) sleep += sleep;
            }
        }
        System.out.printf("Connected to VoltDB node at: %s.\n", server);
    }
819535
def connect(self, server, port=6667):
        
        self.socket.connect((server, port))
        self.lines = self._read_lines()
        for event_handler in list(self.on_connect):
            event_handler(self)
451073
public void startServer() {

    server = new Server(httpPort);
    server.setHandler(wrapHandlers());

    if (isWebSocketInClassPath()) {
      setupForWebSocket();
    }
    try {
      server.start();
      log().info("server started");

      Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownRunnable()));
      
      if (useStdInShutdown) {
        // generally for use in IDE via JettyRun, Use CTRL-D in IDE console to shutdown
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
        while((systemIn.readLine()) != null) {
          // ignore anything except CTRL-D by itself
        }
        System.out.println("Shutdown via CTRL-D");
        System.exit(0);
      }

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
674112
def _init_connection(self):
        
        #detect connectiontype
        if not self.servers:
            raise RuntimeError("No server defined")

        server = random.choice(self.servers)
        if server.scheme in ["http", "https"]:
            self.connection = http_connect(
                [server for server in self.servers if server.scheme in ["http", "https"]],
                timeout=self.timeout, basic_auth=self.basic_auth, max_retries=self.max_retries, retry_time=self.retry_time)
            return
        elif server.scheme == "thrift":
            self.connection = thrift_connect(
                [server for server in self.servers if server.scheme == "thrift"],
                timeout=self.timeout, max_retries=self.max_retries, retry_time=self.retry_time)
242258
def connect(self, timeout=10):
        

        # connect to a local address by default
        # if listening to all addresses (IPv4 or IPv6)
        if self._host == "0.0.0.0":
            host = "127.0.0.1"
        elif self._host == "::":
            host = "::1"
        else:
            host = self._host

        begin = time.time()
        connection_success = False
        last_exception = None
        while time.time() - begin < timeout:
            yield from asyncio.sleep(0.01)
            try:
                self._reader, self._writer = yield from asyncio.wait_for(asyncio.open_connection(host, self._port), timeout=1)
            except (asyncio.TimeoutError, OSError) as e:
                last_exception = e
                continue
            connection_success = True
            break

        if not connection_success:
            raise DynamipsError("Couldn't connect to hypervisor on {}:{} :{}".format(host, self._port, last_exception))
        else:
            log.info("Connected to Dynamips hypervisor after {:.4f} seconds".format(time.time() - begin))

        try:
            version = yield from self.send("hypervisor version")
            self._version = version[0].split("-", 1)[0]
        except IndexError:
            self._version = "Unknown"

        # this forces to send the working dir to Dynamips
        yield from self.set_working_dir(self._working_dir)
555921
private static boolean waitForServerUp(String hostname, int port, long timeout) {
    long start = System.currentTimeMillis();
    while (true) {
      try {
        Socket sock = new Socket(hostname, port);
        BufferedReader reader = null;
        try {
          OutputStream outstream = sock.getOutputStream();
          outstream.write("stat".getBytes());
          outstream.flush();

          Reader isr = new InputStreamReader(sock.getInputStream());
          reader = new BufferedReader(isr);
          String line = reader.readLine();
          if (line != null && line.startsWith("Zookeeper version:")) {
            return true;
          }
        } finally {
          sock.close();
          if (reader != null) {
            reader.close();
          }
        }
      } catch (IOException e) {
        // ignore as this is expected
        logger.info("server " + hostname + ":" + port + " not up " + e);
      }

      if (System.currentTimeMillis() > start + timeout) {
        break;
      }
      try {
        Thread.sleep(250);
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return false;
  }
1295018
protected Socket createSocket(String host, int port) throws SocketException, UnknownHostException
    {
        Socket socket = null;
        int retries = 0;

        // Loop to get a connection or until we've exhausted number of retries
        Throwable cause = null;
        while (retries < CONTEXT.getConfig().getSocketRetries()) {
            try {
            	
            	socket = createSocketFromFactory(SocketFactory.getDefault(), host, port);
            	
                break;
            } catch (UnknownHostException e) {
            	logger.error("Unknown host. Unable to establish connection to " + host + " on port "+ port +". Reason: "+e.getLocalizedMessage(),e);
            	throw e;
            } catch (SocketException e) {
                // Some kind of error, retry if we haven't exceeded max retry
                // count
            	logger.error("Error connecting to " + host + " on port "+ port +". Will retry in " + CONTEXT.getConfig().getSocketRetryWait() / 1000 + " seconds. "
            			       + (CONTEXT.getConfig().getSocketRetries() - retries) +" retries left. Cause: "+e.getLocalizedMessage(),e);

            	cause = e;
            	retries++;
            	
                try {
                    Thread.sleep(CONTEXT.getConfig().getSocketRetryWait());
                    continue;
                } catch (InterruptedException ie) {
                	if(logger.isDebugEnabled()){
                		logger.debug("Sleep awoken early");
                	}
                    continue;
                }

            } catch (IOException e) {
                // Some kind of error, retry if we haven't exceeded max retry
                // count
            	logger.error("Error connecting to " + host + " on port "+ port +". Will retry in "
                        + CONTEXT.getConfig().getSocketRetryWait() / 1000 + " seconds. "
     			       + (CONTEXT.getConfig().getSocketRetries() - retries) +" retries left. Cause: "+e.getLocalizedMessage(),e);

                retries++;
                cause = e;
                continue;
            }
        }

        if (retries >= CONTEXT.getConfig().getSocketRetries()) {
			logger.error("Socket Connect Retries Exhausted.", cause);
           	throw new ConnectException("Socket Connect Retries Exhausted. "+ (cause != null ? "Cause was: "+cause.getLocalizedMessage():""));
        }

        return socket;
    }
1303011
function serverReady (port, ...args) {
  const start = new Date()
  let timeout = serverReady.timeout
  let host, hostOrTimeout, cb

  switch (args.length) {
    case 1:
      [cb] = args
      break
    case 2:
      [hostOrTimeout, cb] = args
      if (typeof hostOrTimeout === 'string') {
        host = hostOrTimeout
      } else {
        timeout = hostOrTimeout
      }
      break
    default:
      [host, timeout, cb] = args
  }

  cb = once(cb)

  let ready = false
  const connect = (port, cb) => {

    const client = net
      .connect({ port, host })
      .on('connect', () => {

        ready = true
        client.destroy()
        cb()

      })
      .on('error', () => {

        client.destroy()

      })
      .once('close', () => {

        if (new Date() - start > timeout) {
          return cb(new Error('Timeout'))
        }

        setTimeout(() => !ready && connect(port, cb), interval)

      })

  }

  connect(port, cb)
}
1345322
public void reconnect (int timeout) throws IOException {
		if (connectHost == null) throw new IllegalStateException("This client has never been connected.");
		connect(timeout, connectHost, connectTcpPort, connectUdpPort);
	}
1324187
@Override
    public void connect(String server, int port, Map<String, Object> connectionParams, IPendingServiceCallback connectCallback, Object[] connectCallArguments) {
        log.debug("connect server: {} port {} connect - params: {} callback: {} args: {}", new Object[] { server, port, connectionParams, connectCallback, Arrays.toString(connectCallArguments) });
        log.info("{}://{}:{}/{}", new Object[] { protocol, server, port, connectionParams.get("app") });
        this.connectionParams = connectionParams;
        this.connectArguments = connectCallArguments;
        if (!connectionParams.containsKey("objectEncoding")) {
            connectionParams.put("objectEncoding", 0);
        }
        this.connectCallback = connectCallback;
        startConnector(server, port);
    }
1065904
public void setServer (String hostname, int[] ports, int[] datagramPorts)
    {
        _hostname = hostname;
        _ports = ports;
        _datagramPorts = datagramPorts;
    }
697836
def _connect(self, servers):
        
        self._do_connect(servers.split(' '))
        self._verify_connection(verbose=True)
580774
private void onServerLinkClose(String hostName)
  {
    ServerHeartbeat server = _root.getServer(hostName);
  
    if (server == null) {
      return;
    }
    
    if (! isHub(server) && ! isHub(_serverSelf)) {
      return;
    }
    
    if (server.onHeartbeatStop()) {
      onServerStop(server);

      if (server.getRack() != null) {
        server.getRack().update();
      }
      
      updateHeartbeats();
    }
  }
808234
def Start(self, hostname, port):
    
    if not self._Open(hostname, port):
      return False

    self._rpc_thread = threading.Thread(
        name=self._THREAD_NAME, target=self._xmlrpc_server.serve_forever)
    self._rpc_thread.start()
    return True
1156149
def wait_for_socket
      return unless Jets.rack?

      retries = 0
      max_retries = 30 # 15 seconds at a delay of 0.5s
      delay = 0.5
      if ENV['C9_USER'] # overrides for local testing
        max_retries = 3
        delay = 3
      end
      begin
        server = TCPSocket.new('localhost', 9292)
        server.close
      rescue Errno::ECONNREFUSED
        puts "Unable to connect to localhost:9292. Delay for #{delay} and will try to connect again."  if ENV['JETS_DEBUG']
        sleep(delay)
        retries += 1
        if retries < max_retries
          retry
        else
          puts "Giving up on trying to connect to localhost:9292"
          return false
        end
      end
      puts "Connected to localhost:9292 successfully"
      true
    end
940412
public void initializeConnection(AppleNotificationServer server) throws CommunicationException, KeystoreException {
		try {
			this.connectionToAppleServer = new ConnectionToNotificationServer(server);
			this.socket = connectionToAppleServer.getSSLSocket();

			if (heavyDebugMode) {
				dumpCertificateChainDescription();
			}
			logger.debug("Initialized Connection to Host: [" + server.getNotificationServerHost() + "] Port: [" + server.getNotificationServerPort() + "]: " + socket);
		} catch (KeystoreException e) {
			throw e;
		} catch (CommunicationException e) {
			throw e;
		} catch (Exception e) {
			throw new CommunicationException("Error creating connection with Apple server", e);
		}
	}
1053586
def _can_connect(host, port=22):  # type: (str, int) -> bool
    
    try:
        logger.debug('Testing connection to host %s', host)
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host,
                       port=port)
        client.close()
        logger.info('Can connect to host %s', host)
        return True
    except Exception as e:
        logger.info('Cannot connect to host %s', host)

        logger.info('Connection failed with exception: \n %s', str(e))
        return False