Connects to the given socket
777778
public function connect(): bool
    {
        if ($this->isConnected()) {
            return true;
        }

        $errno = null;
        $errstr = null;

        // Supress PHP error, we're handling it
        $this->socket = @stream_socket_client(
            $this->getUri(),
            $errno,
            $errstr,
            $this->options['timeout_connect'],
            STREAM_CLIENT_CONNECT,
            $this->getStreamContext()
        );

        if (!$this->socket) {
            throw new \Wrench\Exception\ConnectionException(sprintf(
                'Could not connect to socket: %s (%d)',
                $errstr,
                $errno
            ));
        }

        stream_set_timeout($this->socket, $this->options['timeout_socket']);

        return ($this->connected = true);
    }
258159
function Socket (options) {
    this.options = {
        port: 80
      , secure: false
      , document: 'document' in global ? document : false
      , resource: 'socket.io'
      , transports: io.transports
      , 'connect timeout': 10000
      , 'try multiple transports': true
      , 'reconnect': true
      , 'reconnection delay': 500
      , 'reconnection limit': Infinity
      , 'reopen delay': 3000
      , 'max reconnection attempts': 10
      , 'sync disconnect on unload': true
      , 'auto connect': true
      , 'flash policy port': 10843
    };

    io.util.merge(this.options, options);

    this.connected = false;
    this.open = false;
    this.connecting = false;
    this.reconnecting = false;
    this.namespaces = {};
    this.buffer = [];
    this.doBuffer = false;

    if (this.options['sync disconnect on unload'] &&
        (!this.isXDomain() || io.util.ua.hasCORS)) {
      var self = this;

      io.util.on(global, 'unload', function () {
        self.disconnectSync();
      }, false);
    }

    if (this.options['auto connect']) {
      this.connect();
    }
}
1006811
def connect_socket(root_dir):
    
    # Get config directory where the daemon socket is located
    config_dir = os.path.join(root_dir, '.config/pueue')

    # Create Socket and exit with 1, if socket can't be created
    try:
        client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        socket_path = os.path.join(config_dir, 'pueue.sock')
        if os.path.exists(socket_path):
            client.connect(socket_path)
        else:
            print("Socket doesn't exist")
            raise Exception
    except:
        print("Error connecting to socket. Make sure the daemon is running")
        sys.exit(1)
    return client
171313
function connection(socket, server) {
  var conn = new Connection(socket)
    , tcp = (server instanceof TcpServer);

  var maxclients = this.conf.get(ConfigKey.MAXCLIENTS);
  if(maxclients && (this.state.length + 1 > maxclients)) {

    this.state.emit('rejected', conn.client.addr, maxclients);

    this.log.debug('rejected %s, exceeds maxclients %s',
      conn.client.addr, maxclients);

    function onWrite() {
      socket.end();
    }

    return conn.write(MaxClients, onWrite.bind(this));
  }

  if(tcp) {
    this.log.debug('accepted connection from %s', conn.client.addr);
  }else if(server) {
    this.log.debug('accepted connection to %s', server.name);
  }else if(!server) {
    this.log.debug('accepted connection in %s', process.pid);
  }

  var timeout = this.conf.get(ConfigKey.TIMEOUT);
  if(typeof timeout === 'number' && timeout) {
    this.log.debug('setting idle timeout for client #%s to %ss',
      conn.id, timeout);
    // config is seconds, socket want milliseconds
    socket.setTimeout(timeout * 1000, function onTimeout() {
      // TODO: log client connection timeout
      socket.destroy();
    })
  }

  conn.once('disconnect', this.disconnect.bind(this));
  conn.on('command', this.command);
  this._state.addConnection(conn);
}
248068
def connect_unix
    D "opening connection to #{@socket_path}..."
    s = Timeout.timeout(@open_timeout) { UNIXSocket.open(@socket_path) }
    D "opened"
    @socket = BufferedIO.new(s)
    @socket.read_timeout = @read_timeout
    @socket.continue_timeout = @continue_timeout
    @socket.debug_output = @debug_output
    on_connect
  end
1241424
function connection(socket){
	this.socket = socket;
	if (!!this.options.encoding) socket.setEncoding(this.options.encoding);
	socket.on('data', this.emit.bind(this, 'data'));
	this.emit('connection', socket);
}
1254485
def _connect(self):
        ""
        self.socket = socket.socket()
        self.socket.connect((self.config['host'], self.config['port']))
        self.cmd("NICK %s" % self.config['nick'])
        self.cmd("USER %s %s bla :%s" %
                (self.config['ident'], self.config['host'], self.config['realname']))
256132
def _connect(self):
        """"""
        try:
            while True:
                _LOGGER.info('Trying to connect to %s', self.server_address)
                try:
                    yield from asyncio.wait_for(
                        self.loop.create_connection(
                            lambda: self.protocol, *self.server_address),
                        self.reconnect_timeout, loop=self.loop)
                    self.tcp_check_timer = time.time()
                    self.tcp_disconnect_timer = time.time()
                    self._check_connection()
                    return
                except asyncio.TimeoutError:
                    _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)
                    yield from asyncio.sleep(
                        self.reconnect_timeout, loop=self.loop)
                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)
                    yield from asyncio.sleep(
                        self.reconnect_timeout, loop=self.loop)
        except asyncio.CancelledError:
            _LOGGER.debug(
                'Connect attempt to %s cancelled', self.server_address)
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
405915
def connect(self):
        

        # Make sure we're in client mode
        if self.mode and self.mode != 'client':
            raise ValueError("%s is not in client mode" %
                             self.__class__.__name__)
        self.mode = 'client'

        # If we're connected, nothing to do
        if self.conn:
            return

        # OK, attempt the connection
        fd = socket.create_connection((self.host, self.port))

        # Initialize the connection object
        self.conn = self.connection_class(fd)

        # Authenticate
        try:
            self.conn.send('AUTH', self.authkey)
            cmd, payload = self.conn.recv()
            if cmd != 'OK':
                LOG.error("Failed to authenticate to %s port %s: %s" %
                          (self.host, self.port, payload[0]))
                self.close()
        except Exception:
            exc_type, exc_value, exc_tb = sys.exc_info()

            # Log the error
            if exc_type == ValueError:
                LOG.error("Received bogus response from server: %s" %
                          str(exc_value))
            elif exc_type == ConnectionClosed:
                LOG.error("%s while authenticating to server" %
                          str(exc_value))
            else:
                LOG.exception("Failed to authenticate to server")

            # Close the connection
            self.close()

            # Re-raise the exception
            raise exc_type, exc_value, exc_tb
851019
function Connection(socket) {
  events.EventEmitter.call(this);

  // underlying socket
  this._socket = socket;

  // flag whether this connection is paused
  this._paused = false;

  // external or in-process client connection
  this._tcp = (this._socket instanceof Socket);

  // state information
  this._client = new Client(socket);

  this.data = this.data.bind(this);

  this._socket.once('close', this._close.bind(this));
  this._socket.on('data', this.data);

  // using a tcp socket connection
  if(this._tcp) {
    this.encoder = new Encoder({return_buffers: true})
    this.encoder.on('push', onPush.bind(this));
    this.encoder.pipe(this._socket);
    this.decoder = new Decoder({return_buffers: true});
    this.decoder.on('reply', this.decoded.bind(this));
    this.decoder.on('error', this.decoded.bind(this));

    function onSocketError(err) {
      log.warning(err.message);
    }

    this._socket.on('error', onSocketError.bind(this));
  }

  this.onWrite = this.onWrite.bind(this);
}
516342
def _bind_socket(self, bindaddr):
        """"""
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            sock.bind(bindaddr)
        except Exception:
            self._logger.exception("Unable to bind to %s" % str(bindaddr))
            raise
        sock.listen(self.BACKLOG)
        return sock
1238772
private function connecting() : void
    {
        $this->connected = false;
        $this->closing
            ? $this->closed()->resolve()
            : $this->client = Socket::connect($this->endpoint, $this->events)
        ;
    }
1018050
def connect(self):
        """"""
        self.socket = socket.create_connection(self.address, self.timeout)
903596
void connect(SocketAddress socketAddress, boolean useSSL) {
        ChannelFactory channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());

        ChannelPipeline clientPipeline = NettyChannelPipeline.newPipeline(connection);
        SslHandler sslHandler = null;

        if (useSSL) {
            sslHandler = getClientSSLHandler();
            clientPipeline.addFirst("ssl", sslHandler);
        }

        bootstrap = new ClientBootstrap(channelFactory);
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setPipeline(clientPipeline);

        /*
         * The connection future and the connection itself aren't perfectly
         * synchronized so we have to wait for both to acknowledge that the
         * connection has been made
         */
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        ConnectionStateListener connectedListener = new ConnectionStateListener() {
            @Override
            public void onConnectionConnected() {
                connectedLatch.countDown();
            }

            @Override
            public void onConnectionClosing() {
            }

            @Override
            public void onConnectionClosed() {
            }
        };

        connection.addConnectionStateListener(connectedListener);

        try {
            /* Perform connection */
            ChannelFuture future = bootstrap.connect(socketAddress);

            log.debug("connecting");

            future.await();

            if (future.isSuccess()) {
                /* This await should be very brief */
                connectedLatch.await();

                log.debug("connected successfully");

                if (useSSL) {
                    doSSLHandshake(sslHandler);
                }

                connected = true;
            } else {
                log.debug("connection failed");
                throw new ConnectionException(future.getCause());
            }
        } catch (InterruptedException e) {
            throw new ConnectionException("Interrupted while connecting");
        } finally {
            connection.removeConnectionStateListener(connectedListener);
        }
    }
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;
    }
  }
438251
public function connect()
    {
        $socket = $this->createSocket(
            $this->connection->getHostname(),
            $this->connection->getPort(),
            $this->throttle
        );

        $this->setSocket($socket);
    }