Connect to the backend server.

@return the socket's read/write pair.
332200
private ClientSocket connect()
  {
    if (_maxConnections <= _activeCount.get() + _startingCount.get()) {
      if (log.isLoggable(Level.WARNING)) {
        log.warning(this + " connect exceeded max-connections"
                    + "\n  max-connections=" + _maxConnections
                    + "\n  activeCount=" + _activeCount.get()
                    + "\n  startingCount=" + _startingCount.get());
      }
      
      return null;
    }

    _startingCount.incrementAndGet();

    State state = _state;
    
    if (! state.isInit()) {
      _startingCount.decrementAndGet();
      
      IllegalStateException e = new IllegalStateException(L.l("'{0}' connection cannot be opened because the server pool has not been started.", this));

      log.log(Level.WARNING, e.toString(), e);

      throw e;
    }
    
    if (getPort() <= 0) {
      return null;
    }
    
    long connectionStartTime = CurrentTime.currentTime();

    try {
      ReadWritePair pair = openTCPPair();
      ReadStreamOld rs = pair.getReadStream();
      rs.setEnableReadTime(true);
      
      //rs.setAttribute("timeout", new Integer((int) _loadBalanceSocketTimeout));

      _activeCount.incrementAndGet();
      
      _connectCountTotal.incrementAndGet();

      ClientSocket stream = new ClientSocket(this, _streamCount++,
                                               rs, pair.getWriteStream());

      if (log.isLoggable(Level.FINER))
        log.finer("connect " + stream);

      if (_firstSuccessTime <= 0) {
        if (_state.isStarting()) {
          if (_loadBalanceWarmupTime > 0)
            _state = State.WARMUP;
          else
            _state = State.ACTIVE;

          _firstSuccessTime = CurrentTime.currentTime();
        }

        if (_warmupState < 0)
          _warmupState = 0;
      }

      return stream;
    } catch (IOException e) {
      if (log.isLoggable(Level.FINEST))
        log.log(Level.FINEST, this + " " + e.toString(), e);
      else
        log.finer(this + " " + e.toString());

      failConnect(connectionStartTime);

      return null;
    } finally {
      _startingCount.decrementAndGet();
    }
  }
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());
    }
  }
1335895
public function connect()
    {
        if ($this->connection != null) {
            $this->disconnect();
        }

        if ($this->config['persistent'] == true) {
            $tmp = null;
            $this->connection = @pfsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
        } else {
            $this->connection = fsockopen($this->config['host'], $this->config['port'], $errNum, $errStr, $this->config['timeout']);
        }

        if (!empty($errNum) || !empty($errStr)) {
            $this->error($errStr, $errNum);
        }

        $this->connected = is_resource($this->connection);

        return $this->connected;
    }
982333
def _connect(self):
        
        # we want to mimic what socket.create_connection does to support
        # ipv4/ipv6, but we want to set options prior to calling
        # socket.connect()
        err = None
        for res in socket.getaddrinfo(self.host, self.port, 0,
                                      socket.SOCK_STREAM):
            family, socktype, proto, canonname, socket_address = res
            sock = None
            try:
                sock = socket.socket(family, socktype, proto)
                # TCP_NODELAY
                sock.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY, 1)

                # TCP_KEEPALIVE
                if self.socket_keepalive:
                    sock.setsockopt(socket.SOL_SOCKET,socket.SO_KEEPALIVE, 1)
                    for k, v in iteritems(self.socket_keepalive_options):
                        sock.setsockopt(socket.SOL_TCP, k, v)                

                # set the socket_connect_timeout before we connect
                sock.settimeout(self.socket_connect_timeout)
                # connect
                sock.connect(socket_address)
                # set the socket_timeout now that we're connected
                sock.settimeout(self.socket_timeout)
                return sock                

            except socket.error as _:
                err = _
                if sock is not None:
                    sock.close()
        if err is not None:
            raise err
        raise socket.error("socket.getaddrinfo returned an empty list")
930753
public synchronized void connect() {
        if (state != State.NONE) {
            eventHandler.onError(new WebSocketException("connect() already called"));
            close();
            return;
        }
        getIntializer().setName(getInnerThread(), THREAD_BASE_NAME + "Reader-" + clientId);
        state = State.CONNECTING;
        getInnerThread().start();
    }
1304088
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.server_address)
            try:
                sock = socket.create_connection(
                    self.server_address, self.reconnect_timeout)
            except socket.timeout:
                _LOGGER.error(
                    'Connecting to socket timed out for %s',
                    self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            except OSError:
                _LOGGER.error(
                    'Failed to connect to socket at %s', self.server_address)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                self.tcp_check_timer = time.time()
                self.tcp_disconnect_timer = time.time()
                transport = TCPTransport(
                    sock, lambda: self.protocol, self._check_connection)
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return
644872
private Socket nextSocket() {
    Socket result;
    synchronized (lock) {
      result = nextSocket;
      while (!done && result == null) {
        try {
          lock.wait();
        } catch (InterruptedException e) {
          done = true;
        }
        result = nextSocket;
      }
      nextSocket = null;
    }

    if (result != null) {
      // Java InputStream API is blocking by default with no reliable way to stop pending
      // read() call. Setting the timeout to underlying socket will make socket's underlying
      // read() calls throw SocketTimeoutException which unblocks read(). The exception must
      // be properly handled by calling code.
      try {
        // TODO(buck_team): this does not work with current NGUnixDomainSocket
        // implementation
        result.setSoTimeout(this.heartbeatTimeoutMillis);
      } catch (SocketException e) {
        // this exception might be thrown if socket is already closed
        // so we just return null
        return null;
      }
    }

    return result;
  }
1304616
@Override
	public ServerSocket createServerSocket(int port) throws IOException
    {
    	ServerSocket socket = getSocketFactory().createServerSocket(port,backLog,getListenAddress());
    	if (manageSockets)
    		createdSockets.add(socket);
    	return socket;
    }
306387
def connect(self):
        
        sock = None
        try:
            sock = _configured_socket(self.address, self.opts)
        except socket.error as error:
            if sock is not None:
                sock.close()
            _raise_connection_failure(self.address, error)

        sock_info = SocketInfo(sock, self, self.address)
        if self.handshake:
            sock_info.ismaster(self.opts.metadata, None)
        return sock_info
800514
public int getPort() {
    final Connector[] connectors = this.server.getConnectors();
    checkState(connectors.length >= 1, "Server must have at least 1 connector");

    // The first connector is created upon initializing the server. That's the one that has the port.
    return connectors[0].getLocalPort();
  }
793249
public function connect()
    {
        if (!is_null($this->connection)) {
            return $this->connection;
        }

        $this->connection = $this->socket->open();

        $this->select($this->database);

        return $this->connection;
    }
591856
private void receive() {
    try {
      Socket socket = null;
      BufferedReader reader = null;
      try {
        // connect to the server
        socket = new Socket(host, port);
        reader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        // Until stopped or connection broken continue reading
        String userInput;
        while (!isStopped() && (userInput = reader.readLine()) != null) {
          System.out.println("Received data '" + userInput + "'");
          store(userInput);
        }
      } finally {
        Closeables.close(reader, /* swallowIOException = */ true);
        Closeables.close(socket,  /* swallowIOException = */ true);
      }
      // Restart in an attempt to connect again when server is active again
      restart("Trying to connect again");
    } catch(ConnectException ce) {
      // restart if could not connect to server
      restart("Could not connect", ce);
    } catch(Throwable t) {
      restart("Error receiving data", t);
    }
  }
399976
protected function connect()
    {
        $this->socket = new Net_Notifier_Socket_Client(
            sprintf(
                'tcp://%s:%s',
                $this->host,
                $this->port
            ),
            $this->timeout / 1000
        );

        $this->connection = new Net_Notifier_WebSocket_Connection(
            $this->socket
        );

        $this->connection->startHandshake(
            $this->host,
            $this->port,
            $this->resource,
            array(Net_Notifier_WebSocket::PROTOCOL)
        );

        // read handshake response
        $state = $this->connection->getState();
        while ($state < Net_Notifier_WebSocket_Connection::STATE_OPEN) {

            $read = array($this->socket->getRawSocket());

            $result = stream_select(
                $read,
                $write = null,
                $except = null,
                null
            );

            if ($result === 1) {
                $this->connection->read(self::READ_BUFFER_LENGTH);
            }

            $state = $this->connection->getState();
        }
    }
599868
def connect(self):
        """"""
        log.info('Connecting socket on %s:%d' % (self.server, self.port))
        tries = 0
        while not self._socket and tries < 10:
            try:
                time.sleep(.2 * tries)
                self._socket = Socket((self.server, self.port))
            except socket.error:
                tries += 1
                log.warning(
                    'You must start/install wdb.server '
                    '(Retrying on %s:%d) [Try #%d/10]' %
                    (self.server, self.port, tries)
                )
                self._socket = None

        if not self._socket:
            log.warning('Could not connect to server')
            return

        Wdb._sockets.append(self._socket)
        self._socket.send_bytes(self.uuid.encode('utf-8'))
544974
@Override
  public void open() {
    try {
      if (this.isOpened() == false) {
        System.out.println(formatVersionInfo() + " Opening ...");

        InetSocketAddress inetSocketAddress = new InetSocketAddress(this.hostName, this.portNo);
        this.pizzaConnection = new Socket();
        this.pizzaConnection.connect(inetSocketAddress, TIMEOUT);
        this.setBufferedOutputStream(new BufferedOutputStream(this.pizzaConnection.getOutputStream(), this.getBufferSize()));
        this.setTracePrintStream(new TracePrintStream(this.getBufferedOutputStream(), this.getThreadMap()));

        sendUserCredentials();
        this.getTracePrintStream().printf("--> TraceLog opened!%n");
        this.getTracePrintStream().printf("    Time     : %tc%n", new Date());
        this.getTracePrintStream().printf("    Bufsize  : %d%n", this.getBufferSize());
        this.getTracePrintStream().printf("    Autoflush: %b%n%n", this.isAutoflush());

        this.setOpened(true);
      }
      else {
        System.err.println("WARNING: Tracelog is opened already.");
      }
    }
    catch (IOException ex) {
      ex.printStackTrace(System.err);
    }
  }
777019
public function connect()
    {
        Debug::Log(Debug::DEBUG, 'socket_connect()');
        if (!$this->context) {
            $context = stream_context_create();
        } else {
            $context = $this->context;
        }
        Debug::Log(Debug::DEBUG, 'socket_connect(): connect to='.$this->address);

        $this->socket = stream_socket_client(
            $this->address,
            $errno,
            $errstr,
            60,
            STREAM_CLIENT_CONNECT,
            $context
        );
        if (!$this->socket) {
            Debug::Log(Debug::DEBUG, "stream_socket_client() {$errno}, {$errstr}");
            return false;
        }
        stream_set_timeout($this->socket,  5);

        #TODO:  MUST BE IN BLOCKING MODE
        #$this->set_blocking();

        return true;
    }
437273
protected Server getReadServer() {
        Server[] servers = readServers;

        return servers[readSequence.incrementAndGet(servers.length)];
    }