Establishes a connection with the server.
165469
async def connect(self, timeout=None, ssl=None):
        
        await self._connect(timeout=timeout, ssl=ssl)
        self._connected = True

        self._send_task = self._loop.create_task(self._send_loop())
        self._recv_task = self._loop.create_task(self._recv_loop())
1110766
private function establishSocketConnection()
    {
        $host = $this->params['host'];
        if (!empty($this->params['protocol'])) {
            $host = $this->params['protocol'].'://'.$host;
        }
        $timeout = 15;
        if (!empty($this->params['timeout'])) {
            $timeout = $this->params['timeout'];
        }
        $options = [];
        if (!empty($this->params['sourceIp'])) {
            $options['socket']['bindto'] = $this->params['sourceIp'].':0';
        }

        if (isset($this->params['stream_context_options'])) {
            $options = array_merge($options, $this->params['stream_context_options']);
        }
        $streamContext = stream_context_create($options);
        $this->stream = @stream_socket_client($host.':'.$this->params['port'], $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $streamContext);
        if (false === $this->stream) {
            throw new Swift_TransportException(
                'Connection could not be established with host '.$this->params['host'].
                ' ['.$errstr.' #'.$errno.']'
                );
        }
        if (!empty($this->params['blocking'])) {
            stream_set_blocking($this->stream, 1);
        } else {
            stream_set_blocking($this->stream, 0);
        }
        stream_set_timeout($this->stream, $timeout);
        $this->in = &$this->stream;
        $this->out = &$this->stream;
    }
242891
def connect(self):
    """"""
    if self._connected or self.is_alive():
      raise ConnectionExistsError("Already connected")
    # After starting the thread we wait for it to post us
    # an event signifying that connection is established. This
    # ensures that the caller only resumes when we are fully connected.
    self.start()
    with self._lock:
      self._connect_cond.wait_for(lambda: self._connected)
846638
def _start_connection_setup(self):
        """"""
        logger.info('We are connected[%s], request connection setup',
                    self.link_uri)
        self.platform.fetch_platform_informations(self._platform_info_fetched)
529101
public function connect()
    {
        $this->isBound = false;
        $this->connection = $this->driver->connect(
            $this->configuration['hostname'],
            $this->configuration['port'],
            $this->configuration['withSSL'],
            $this->configuration['withTLS']
        );

        foreach ($this->configuration['options'] as $key => $value) {
            $this->connection->setOption($key, $value);
        }
    }
689093
def _setup():
    
    _SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    _SOCKET.bind(('', PORT))
    udp = threading.Thread(target=_listen, daemon=True)
    udp.start()
1206267
public function connect()
    {
        /*
         The Server MUST process a second CONNECT Packet sent from a Client as a protocol violation
         and disconnect the Client [MQTT-3.1.0-2]

         So CONNECT SHOULD be a blocking connection.
         */
        $this->socket->connect(function ($cli) {
            Debug::Log(Debug::INFO, 'connect(): Connection established.');
            /**
             * @var Message\CONNECT $connectobj
             */
            $connectobj = $this->getMessageObject(Message::CONNECT);

            if (!$this->connect_clean && empty($this->clientid)) {
                throw new Exception('Client id must be provided if Clean Session flag is set false.');
            }

            # default client id
            if (empty($this->clientid)) {
                $this->clientid = 'mqtt' . substr(md5(uniqid('mqtt', true)), 8, 16);
            } else {
                $connectobj->setClientId($this->clientid);
            }
            Debug::Log(Debug::DEBUG, 'connect(): clientid=' . $this->clientid);

            $connectobj->setKeepalive($this->keepalive);
            Debug::Log(Debug::DEBUG, 'connect(): keepalive=' . $this->keepalive);

            $connectobj->setAuth($this->username, $this->password);
            Debug::Log(Debug::DEBUG, 'connect(): username=' . $this->username . ' password=' . $this->password);

            $connectobj->setClean($this->connect_clean);

            if ($this->connect_will instanceof Will) {
                $connectobj->setWill($this->connect_will);
            }

            $length = 0;

            $bytes_written = $this->message_write($connectobj, $length);
            Debug::Log(Debug::DEBUG, 'connect(): bytes written=' . $bytes_written);

            $this->keepalive_time = swoole_timer_tick($this->keepalive * 500, [$this, 'keepalive']);
        }, [$this, 'onReceive'],function (){
            secho("MQTT", "连接mqtt服务器失败,正在重试");
            swoole_timer_after(1000,[$this,'connect']);
        },function (){
            if ($this->keepalive_time!=null) {
                swoole_timer_clear($this->keepalive_time);
                $this->keepalive_time = null;
            }
            $this->connect();
        });
    }
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))
349257
public void connect() {

        readyState = ReadyState.CONNECTING;

        try {
            if (webSocketHandler == null) {
                webSocketHandler = new WebSocketHandlerAdapter();
            }

            container.connectToServer(new SimpleWebSocketClientEndpoint(), ClientEndpointConfig.Builder.create().build(), websocketURI);
        } catch (Exception e) {

            readyState = ReadyState.CLOSED;
            // throws DeploymentException, IOException
            throw new RuntimeException("could not establish connection");

        }
    }
702482
protected function createConnection()
  {
      $config = $this['config'];
    /*
     * Attaches the Connection instance to the container
     */
    $this->applyInstance('connection', new Connection(
        $config['app.connection.username'],
        $config['app.connection.oauth'],
        $config['app.connection.ircServer.hostname'],
        $config['app.connection.ircServer.port']
      )
    );
  }
321167
def establish_connection(self):
        """"""
        conninfo = self.connection
        if not conninfo.hostname:
            raise KeyError("Missing hostname for AMQP connection.")
        if conninfo.userid is None:
            raise KeyError("Missing user id for AMQP connection.")
        if conninfo.password is None:
            raise KeyError("Missing password for AMQP connection.")
        if not conninfo.port:
            conninfo.port = self.default_port
        conn = amqp.Connection(host=conninfo.hostname,
                               port=conninfo.port,
                               userid=conninfo.userid,
                               password=conninfo.password,
                               virtual_host=conninfo.virtual_host)
        return conn
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)
134771
public void start() {
		if (socket == null) {
			throw new RuntimeException("Cannot bind a server that has not been initialized!");
		}
		running = true;

		Thread t = new Thread(this);
		t.setName("HttpServer");
		t.start();
	}
673533
def _connect(self):
        """"""
        if sys.version_info[:2] < (2,6):
            self._conn = httplib.HTTPConnection(self._host, self._port)
        else:
            self._conn = httplib.HTTPConnection(self._host, self._port, 
                                                False, defaultTimeout)
64273
private function connect()
    {
        $this->conn = parent::getConn();
        $this->create = $this->conn->prepare($this->create);
    }
383098
public void connectServer(Connection connection) {
    threadContext.checkThread();

    // Handlers for all request types are registered since requests can be proxied between servers.
    // Note we do not use method references here because the "state" variable changes over time.
    // We have to use lambdas to ensure the request handler points to the current state.
    connection.handler(RegisterRequest.class, (Function<RegisterRequest, CompletableFuture<RegisterResponse>>) request -> state.register(request));
    connection.handler(ConnectRequest.class, (Function<ConnectRequest, CompletableFuture<ConnectResponse>>) request -> state.connect(request, connection));
    connection.handler(KeepAliveRequest.class, (Function<KeepAliveRequest, CompletableFuture<KeepAliveResponse>>) request -> state.keepAlive(request));
    connection.handler(UnregisterRequest.class, (Function<UnregisterRequest, CompletableFuture<UnregisterResponse>>) request -> state.unregister(request));
    connection.handler(ResetRequest.class, (Consumer<ResetRequest>) request -> state.reset(request));
    connection.handler(ConfigureRequest.class, (Function<ConfigureRequest, CompletableFuture<ConfigureResponse>>) request -> state.configure(request));
    connection.handler(InstallRequest.class, (Function<InstallRequest, CompletableFuture<InstallResponse>>) request -> state.install(request));
    connection.handler(JoinRequest.class, (Function<JoinRequest, CompletableFuture<JoinResponse>>) request -> state.join(request));
    connection.handler(ReconfigureRequest.class, (Function<ReconfigureRequest, CompletableFuture<ReconfigureResponse>>) request -> state.reconfigure(request));
    connection.handler(LeaveRequest.class, (Function<LeaveRequest, CompletableFuture<LeaveResponse>>) request -> state.leave(request));
    connection.handler(AppendRequest.class, (Function<AppendRequest, CompletableFuture<AppendResponse>>) request -> state.append(request));
    connection.handler(PollRequest.class, (Function<PollRequest, CompletableFuture<PollResponse>>) request -> state.poll(request));
    connection.handler(VoteRequest.class, (Function<VoteRequest, CompletableFuture<VoteResponse>>) request -> state.vote(request));
    connection.handler(CommandRequest.class, (Function<CommandRequest, CompletableFuture<CommandResponse>>) request -> state.command(request));
    connection.handler(QueryRequest.class, (Function<QueryRequest, CompletableFuture<QueryResponse>>) request -> state.query(request));

    connection.onClose(stateMachine.executor().context().sessions()::unregisterConnection);
  }
444778
public function connect()
    {
        $this->conn = imap_open($this->server, $this->user, $this->pass);
    }