// Connect will create a connection to the message broker, by default
// it will attempt to connect at v3.1.1 and auto retry at v3.1 if that
// fails
968687
func (c *client) Connect() Token {
	var err error
	t := newToken(packets.Connect).(*ConnectToken)
	DEBUG.Println(CLI, "Connect()")

	c.obound = make(chan *PacketAndToken, c.options.MessageChannelDepth)
	c.oboundP = make(chan *PacketAndToken, c.options.MessageChannelDepth)
	c.ibound = make(chan packets.ControlPacket)

	go func() {
		c.persist.Open()

		c.setConnected(connecting)
		c.errors = make(chan error, 1)
		c.stop = make(chan struct{})

		var rc byte
		protocolVersion := c.options.ProtocolVersion

		if len(c.options.Servers) == 0 {
			t.setError(fmt.Errorf("No servers defined to connect to"))
			return
		}

		for _, broker := range c.options.Servers {
			cm := newConnectMsgFromOptions(&c.options, broker)
			c.options.ProtocolVersion = protocolVersion
		CONN:
			DEBUG.Println(CLI, "about to write new connect msg")
			c.conn, err = openConnection(broker, c.options.TLSConfig, c.options.ConnectTimeout, c.options.HTTPHeaders)
			if err == nil {
				DEBUG.Println(CLI, "socket connected to broker")
				switch c.options.ProtocolVersion {
				case 3:
					DEBUG.Println(CLI, "Using MQTT 3.1 protocol")
					cm.ProtocolName = "MQIsdp"
					cm.ProtocolVersion = 3
				case 0x83:
					DEBUG.Println(CLI, "Using MQTT 3.1b protocol")
					cm.ProtocolName = "MQIsdp"
					cm.ProtocolVersion = 0x83
				case 0x84:
					DEBUG.Println(CLI, "Using MQTT 3.1.1b protocol")
					cm.ProtocolName = "MQTT"
					cm.ProtocolVersion = 0x84
				default:
					DEBUG.Println(CLI, "Using MQTT 3.1.1 protocol")
					c.options.ProtocolVersion = 4
					cm.ProtocolName = "MQTT"
					cm.ProtocolVersion = 4
				}
				cm.Write(c.conn)

				rc, t.sessionPresent = c.connect()
				if rc != packets.Accepted {
					if c.conn != nil {
						c.conn.Close()
						c.conn = nil
					}
					//if the protocol version was explicitly set don't do any fallback
					if c.options.protocolVersionExplicit {
						ERROR.Println(CLI, "Connecting to", broker, "CONNACK was not CONN_ACCEPTED, but rather", packets.ConnackReturnCodes[rc])
						continue
					}
					if c.options.ProtocolVersion == 4 {
						DEBUG.Println(CLI, "Trying reconnect using MQTT 3.1 protocol")
						c.options.ProtocolVersion = 3
						goto CONN
					}
				}
				break
			} else {
				ERROR.Println(CLI, err.Error())
				WARN.Println(CLI, "failed to connect to broker, trying next")
				rc = packets.ErrNetworkError
			}
		}

		if c.conn == nil {
			ERROR.Println(CLI, "Failed to connect to a broker")
			c.setConnected(disconnected)
			c.persist.Close()
			t.returnCode = rc
			if rc != packets.ErrNetworkError {
				t.setError(packets.ConnErrors[rc])
			} else {
				t.setError(fmt.Errorf("%s : %s", packets.ConnErrors[rc], err))
			}
			return
		}

		c.options.protocolVersionExplicit = true

		if c.options.KeepAlive != 0 {
			atomic.StoreInt32(&c.pingOutstanding, 0)
			c.lastReceived.Store(time.Now())
			c.lastSent.Store(time.Now())
			c.workers.Add(1)
			go keepalive(c)
		}

		c.incomingPubChan = make(chan *packets.PublishPacket, c.options.MessageChannelDepth)
		c.msgRouter.matchAndDispatch(c.incomingPubChan, c.options.Order, c)

		c.setConnected(connected)
		DEBUG.Println(CLI, "client is connected")
		if c.options.OnConnect != nil {
			go c.options.OnConnect(c)
		}

		c.workers.Add(4)
		go errorWatch(c)
		go alllogic(c)
		go outgoing(c)
		go incoming(c)

		// Take care of any messages in the store
		if c.options.CleanSession == false {
			c.resume(c.options.ResumeSubs)
		} else {
			c.persist.Reset()
		}

		DEBUG.Println(CLI, "exit startClient")
		t.flowComplete()
	}()
	return t
}
288591
func (c *UDPClient) Connect() error {
	c.t.Go(func() error {
		return c.runRequestQueue()
	})
	udp, err := net.DialTimeout("udp", c.addr, c.timeout)
	if err != nil {
		return err
	}
	c.conn = udp
	return nil
}
1129436
func (f *Adaptor) Connect() (err error) {
	if f.conn == nil {
		sp, e := f.PortOpener(f.Port())
		if e != nil {
			return e
		}
		f.conn = sp
	}
	if err = f.Board.Connect(f.conn); err != nil {
		return err
	}

	f.Board.On("SysexResponse", func(data interface{}) {
		f.Publish("SysexResponse", data)
	})

	return
}
1189343
func (c *Client) Connect(config *Config) (ConnectFuture, error) {
	if config == nil {
		panic("no config specified")
	}

	c.mutex.Lock()
	defer c.mutex.Unlock()

	// check if already connecting
	if atomic.LoadUint32(&c.state) >= clientConnecting {
		return nil, ErrClientAlreadyConnecting
	}

	// save config
	c.config = config

	// parse url
	urlParts, err := url.ParseRequestURI(config.BrokerURL)
	if err != nil {
		return nil, err
	}

	// check client id
	if !config.CleanSession && config.ClientID == "" {
		return nil, ErrClientMissingID
	}

	// parse keep alive
	keepAlive, err := time.ParseDuration(config.KeepAlive)
	if err != nil {
		return nil, err
	}

	// allocate and initialize tracker
	c.keepAlive = keepAlive
	c.tracker = NewTracker(keepAlive)

	// dial broker (with custom dialer if present)
	if config.Dialer != nil {
		c.conn, err = config.Dialer.Dial(config.BrokerURL)
		if err != nil {
			return nil, err
		}
	} else {
		c.conn, err = transport.Dial(config.BrokerURL)
		if err != nil {
			return nil, err
		}
	}

	// set to connecting as from this point the client cannot be reused
	atomic.StoreUint32(&c.state, clientConnecting)

	// from now on the connection has been used and we have to close the
	// connection and cleanup on any subsequent error

	// save clean
	c.clean = config.CleanSession

	// reset store
	if c.clean {
		err = c.Session.Reset()
		if err != nil {
			return nil, c.cleanup(err, true, false)
		}
	}

	// allocate packet
	connect := packet.NewConnect()
	connect.ClientID = config.ClientID
	connect.KeepAlive = uint16(keepAlive.Seconds())
	connect.CleanSession = config.CleanSession

	// check for credentials
	if urlParts.User != nil {
		connect.Username = urlParts.User.Username()
		connect.Password, _ = urlParts.User.Password()
	}

	// set will
	connect.Will = config.WillMessage

	// create new ConnectFuture
	c.connectFuture = future.New()

	// send connect packet
	err = c.send(connect, false)
	if err != nil {
		return nil, c.cleanup(err, false, false)
	}

	// start process routine
	c.tomb.Go(c.processor)

	// wrap future
	wrappedFuture := &connectFuture{c.connectFuture}

	return wrappedFuture, nil
}
928271
func (this *ZookeeperCoordinator) Connect() (err error) {
	var connectionEvents <-chan zk.Event
	for i := 0; i <= this.config.MaxRequestRetries; i++ {
		this.zkConn, connectionEvents, err = this.tryConnect()
		if err == nil {
			go this.listenConnectionEvents(connectionEvents)
			return
		}
		Tracef(this, "Zookeeper connect failed after %d-th retry", i)
		time.Sleep(this.config.RequestBackoff)
	}

	return
}
586901
func (c *Client) Connect() (client.Session, error) {
	if c.conn == nil {
		if err := c.initConnection(); err != nil {
			return nil, err
		}
	}
	return &Session{c.conn, c.ch}, nil
}
147857
func (r *BinaryInstantiateREST) Connect(ctx context.Context, name string, options runtime.Object, responder rest.Responder) (http.Handler, error) {
	return &binaryInstantiateHandler{
		r:         r,
		responder: responder,
		ctx:       ctx,
		name:      name,
		options:   options.(*buildapi.BinaryBuildRequestOptions),
	}, nil
}
615413
func (conn *Connection) Connect(ctx context.Context) (err error) {
	obs := prometheus.NewTimer(connInitialConnectTime)
	defer obs.ObserveDuration()

	conn.conMu.Lock()
	defer conn.conMu.Unlock()

	var tlsc *tls.Config

	if !conn.choria.Config.DisableTLS {
		tlsc, err = conn.choria.TLSConfig()
		if err != nil {
			err = fmt.Errorf("Could not create TLS Config: %s", err)
			return err
		}
	}

	urls := []string{}
	var url *url.URL

	servers, err := conn.servers()
	if err != nil {
		err = fmt.Errorf("Could not resolve servers during initial connect: %s", err)
	}

	for _, server := range servers {
		url, err = server.URL()
		if err != nil {
			err = fmt.Errorf("Could not determine URL for server %#v", server)
			return
		}

		urls = append(urls, url.String())
	}

	options := []nats.Option{
		nats.MaxReconnects(-1),
		nats.Name(conn.name),

		// This is specifically set quite small, just about enough to handle short
		// reconnects rather than the 8MB long buffer that's default.  30 000 nodes
		// each sending several MB after reconnect is not what anyone wants
		nats.ReconnectBufSize(10 * 1024),

		// nats.SetPend
		nats.DisconnectHandler(func(nc *nats.Conn) {
			err = nc.LastError()

			if err != nil {
				conn.logger.Warnf("NATS client connection got disconnected: %s", nc.LastError())
			}
		}),

		nats.ReconnectHandler(func(nc *nats.Conn) {
			conn.logger.Warnf("NATS client reconnected after a previous disconnection, connected to %s", nc.ConnectedUrl())
			connReconnectCtr.Inc()
		}),

		nats.ClosedHandler(func(nc *nats.Conn) {
			err = nc.LastError()
			if err != nil {
				conn.logger.Warnf("NATS client connection closed: %s", nc.LastError())
			}
			connClosedCtr.Inc()
		}),

		nats.ErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
			conn.logger.Errorf("NATS client on %s encountered an error: %s", nc.ConnectedUrl(), err)
			connErrorCtr.Inc()
		}),
	}

	if !conn.choria.Config.DisableTLS {
		options = append(options, nats.Secure(tlsc))
	}

	if !conn.choria.Config.Choria.RandomizeMiddlewareHosts {
		options = append(options, nats.DontRandomize())
	}

	try := 0

	for {
		try++

		conn.nats, err = nats.Connect(strings.Join(urls, ", "), options...)
		if err != nil {
			connInitialConnectCtr.Inc()

			conn.logger.Warnf("Initial connection to the NATS broker cluster failed: %s", err)

			if ctx.Err() != nil {
				err = fmt.Errorf("Initial connection cancelled due to shut down")
				return
			}

			s := backoff.FiveSec.Duration(try)
			conn.logger.Infof("Sleeping %s after failed connection attempt %d", s, try)
			time.Sleep(s)

			continue
		}

		conn.logger.Debugf("Connected to %s", conn.nats.ConnectedUrl())

		break
	}

	return
}
287382
func (w *Writer) connect() (err error) {
	if w.conn != nil {
		// ignore err from close, it makes sense to continue anyway
		w.conn.close()
		w.conn = nil
	}

	var c net.Conn
	c, err = net.Dial(w.network, w.raddr)
	if err == nil {
		w.conn = &netConn{conn: c}
		if w.hostname == "" {
			w.hostname = c.LocalAddr().String()
		}
	}
	return
}
11588
func (c *socks5MuxBindConnector) Connect(conn net.Conn, addr string, options ...ConnectOption) (net.Conn, error) {
	accepter, ok := conn.(Accepter)
	if !ok {
		return nil, errors.New("wrong connection type")
	}

	return accepter.Accept()
}
1022302
func (a *Adaptor) Connect() (err error) {
	a.client = paho.NewClient(a.createClientOptions())
	if token := a.client.Connect(); token.Wait() && token.Error() != nil {
		err = multierror.Append(err, token.Error())
	}

	return
}
879131
func (c *Client) Connect() (client.Session, error) {
	if c.mgoSession == nil {
		if err := c.initConnection(); err != nil {
			return nil, err
		}
	}
	return c.session(), nil
}
416411
func (pool *hostConnPool) connect() (err error) {
	// TODO: provide a more robust connection retry mechanism, we should also
	// be able to detect hosts that come up by trying to connect to downed ones.
	// try to connect
	var conn *Conn
	reconnectionPolicy := pool.session.cfg.ReconnectionPolicy
	for i := 0; i < reconnectionPolicy.GetMaxRetries(); i++ {
		conn, err = pool.session.connect(pool.host, pool)
		if err == nil {
			break
		}
		if opErr, isOpErr := err.(*net.OpError); isOpErr {
			// if the error is not a temporary error (ex: network unreachable) don't
			//  retry
			if !opErr.Temporary() {
				break
			}
		}
		if gocqlDebug {
			Logger.Printf("connection failed %q: %v, reconnecting with %T\n",
				pool.host.ConnectAddress(), err, reconnectionPolicy)
		}
		time.Sleep(reconnectionPolicy.GetInterval(i))
	}

	if err != nil {
		return err
	}

	if pool.keyspace != "" {
		// set the keyspace
		if err = conn.UseKeyspace(pool.keyspace); err != nil {
			conn.Close()
			return err
		}
	}

	// add the Conn to the pool
	pool.mu.Lock()
	defer pool.mu.Unlock()

	if pool.closed {
		conn.Close()
		return nil
	}

	pool.conns = append(pool.conns, conn)

	return nil
}
574765
func (o Options) Connect() (*Conn, error) {
	nc := &Conn{Opts: o}

	// Some default options processing.
	if nc.Opts.MaxPingsOut == 0 {
		nc.Opts.MaxPingsOut = DefaultMaxPingOut
	}
	// Allow old default for channel length to work correctly.
	if nc.Opts.SubChanLen == 0 {
		nc.Opts.SubChanLen = DefaultMaxChanLen
	}
	// Default ReconnectBufSize
	if nc.Opts.ReconnectBufSize == 0 {
		nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
	}
	// Ensure that Timeout is not 0
	if nc.Opts.Timeout == 0 {
		nc.Opts.Timeout = DefaultTimeout
	}

	// Check first for user jwt callback being defined and nkey.
	if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
		return nil, ErrNkeyAndUser
	}

	// Check if we have an nkey but no signature callback defined.
	if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
		return nil, ErrNkeyButNoSigCB
	}

	// Allow custom Dialer for connecting using DialTimeout by default
	if nc.Opts.Dialer == nil {
		nc.Opts.Dialer = &net.Dialer{
			Timeout: nc.Opts.Timeout,
		}
	}

	if err := nc.setupServerPool(); err != nil {
		return nil, err
	}

	// Create the async callback handler.
	nc.ach = &asyncCallbacksHandler{}
	nc.ach.cond = sync.NewCond(&nc.ach.mu)

	if err := nc.connect(); err != nil {
		return nil, err
	}

	// Spin up the async cb dispatcher on success
	go nc.ach.asyncCBDispatcher()

	return nc, nil
}
393530
func (c *Client) Connect(conn net.Conn, addr string, options ...ConnectOption) (net.Conn, error) {
	return c.Connector.Connect(conn, addr, options...)
}
1184517
func (c *Client) Connect() {
	for c.GetState() == DisconnectedState {
		go c.resubscribe()
		c.doConnection()
		time.Sleep(c.policy.Next())
	}

	c.setState(ClosedState)
}
649262
func Connect(address string, dialOptions []grpc.DialOption) (*grpc.ClientConn, error) {
	u, err := url.Parse(address)
	if err == nil && (!u.IsAbs() || u.Scheme == "unix") {
		dialOptions = append(dialOptions,
			grpc.WithDialer(
				func(addr string, timeout time.Duration) (net.Conn, error) {
					return net.DialTimeout("unix", u.Path, timeout)
				}))
	}

	dialOptions = append(dialOptions, grpc.WithBackoffMaxDelay(time.Second))
	conn, err := grpc.Dial(address, dialOptions...)
	if err != nil {
		return nil, err
	}

	// We wait for 1 minute until conn.GetState() is READY.
	// The interval for this check is 1 second.
	if err := util.WaitFor(1*time.Minute, 10*time.Millisecond, func() (bool, error) {
		if conn.GetState() == connectivity.Ready {
			return false, nil
		}
		return true, nil
	}); err != nil {
		return nil, fmt.Errorf("Connection timed out")
	}

	return conn, nil
}