Establishes the connection to the given WebSocket Server Address.
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");

        }
    }
985335
def _register(self):
        """"""
        logger.debug('register on %s', "ws://{}:{}".format(self.ip, self.port));
        try:
            websocket = yield from websockets.connect(
                "ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)

        except:
            logger.error('register failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
            return False

        logger.debug('register websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));

        try:
            yield from self._send_register_payload(websocket)

        finally:
            logger.debug('close register connection to %s', "ws://{}:{}".format(self.ip, self.port));
            yield from websocket.close()
210817
ChannelFuture connect(final InetSocketAddress serverSocketAddress) {
		checkState(bootstrap != null, "Client has not been initialized yet.");

		// --------------------------------------------------------------------
		// Child channel pipeline for accepted connections
		// --------------------------------------------------------------------

		bootstrap.handler(new ChannelInitializer<SocketChannel>() {
			@Override
			public void initChannel(SocketChannel channel) throws Exception {

				// SSL handler should be added first in the pipeline
				if (clientSSLFactory != null) {
					SslHandler sslHandler = clientSSLFactory.createNettySSLHandler(
							serverSocketAddress.getAddress().getCanonicalHostName(),
							serverSocketAddress.getPort());
					channel.pipeline().addLast("ssl", sslHandler);
				}
				channel.pipeline().addLast(protocol.getClientChannelHandlers());
			}
		});

		try {
			return bootstrap.connect(serverSocketAddress);
		}
		catch (ChannelException e) {
			if ((e.getCause() instanceof java.net.SocketException &&
					e.getCause().getMessage().equals("Too many open files")) ||
				(e.getCause() instanceof ChannelException &&
						e.getCause().getCause() instanceof java.net.SocketException &&
						e.getCause().getCause().getMessage().equals("Too many open files")))
			{
				throw new ChannelException(
						"The operating system does not offer enough file handles to open the network connection. " +
								"Please increase the number of available file handles.", e.getCause());
			}
			else {
				throw e;
			}
		}
	}
133660
def connect_tcp(self, address, port):
        """"""
        info('Connecting to TCP address: %s:%d', address, port)
        self._connect_tcp(address, port)
289064
def connectToServer(self):
    """"""
    self.rtspSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
      self.rtspSocket.connect((self.serverAddr, self.serverPort))
    except:
      tkinter.messagebox.showwarning('Connection Failed', 'Connection to \'%s\' failed.' %self.serverAddr)
1100348
def create_connection(self, room, ws_url, agent, cookies):
        """"""

        urlparts = urlsplit(ws_url)
        req = Request("GET", ws_url)
        cookies = get_cookie_header(cookies, req)
        if cookies:
            headers = dict(Cookie=cookies)
        else:
            headers = None

        factory = WebSocketClientFactory(ws_url, headers=headers, loop=self.loop)
        factory.useragent = agent
        factory.protocol = lambda: room
        conn = self.loop.create_connection(
            factory,
            host=urlparts.netloc,
            port=urlparts.port or 443,
            ssl=urlparts.scheme == "wss",
        )
        asyncio.ensure_future(conn, loop=self.loop)
1044222
public void connect() throws Exception {
        logger.debug("[connect] initializing new connection");

        if (timer != null) {
            timer.cancel();
        }

        if (isConnected()) {
            return;
        }

        synchronized (webSocketHandler.getNotifyConnectionObject()) {
            webSocketConnectionManager.start();

            try {
                webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT));
            }
            catch (InterruptedException e) {
                onConnectionClosed();
                logger.debug("[connect] not open");
                throw new Exception("websocket connection not open");
            }

            if (!isConnected()) {
                onConnectionClosed();
                logger.debug("[connect] timeout");
                throw new Exception("websocket connection timeout");
            }
        }
    }
497441
function Server(config) {
  utils.verbose(config.verbose)

  this._wsStarted = false
  this._wsStopped = false

  this._wsConfig = config
  this._wsServer = new websocket.server()

  this._onRequest = config.onRequest

  this._wsServer.addListener("request", this._onRequest)
  this._wsServer.addListener("connect", onConnect)
}
624609
def make_connection(self, transport, address):
        """"""
        self.connected = True
        self.transport = transport
        self.connection_made(address)
1040781
public void connect() throws Exception {
        logger.debug("[connect] initializing new connection");

        synchronized (webSocketHandler.getNotifyConnectionObject()) {
            webSocketConnectionManager.start();

            try {
                webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT));
            }
            catch (InterruptedException e) {
                throw new Exception("websocket connection not open");
            }

            if (!isConnected()) {
                throw new Exception("websocket connection timeout (uri = " + uriTemplate + ")");
            }
        }
    }
710212
def start(self):
        
        super(BitfinexWSS, self).start()

        log.info("BitfinexWSS.start(): Initializing Websocket connection..")
        while self.conn is None:
            try:
                self.conn = create_connection(self.addr, timeout=10)
            except WebSocketTimeoutException:
                self.conn = None
                print("Couldn't create websocket connection - retrying!")

        log.info("BitfinexWSS.start(): Initializing receiver thread..")
        if not self.receiver_thread:
            self.receiver_thread = Thread(target=self.receive, name='Receiver Thread')
            self.receiver_thread.start()
        else:
            log.info("BitfinexWSS.start(): Thread not started! "
                     "self.receiver_thread is populated!")

        log.info("BitfinexWSS.start(): Initializing processing thread..")
        if not self.processing_thread:
            self.processing_thread = Thread(target=self.process, name='Processing Thread')
            self.processing_thread.start()
        else:
            log.info("BitfinexWSS.start(): Thread not started! "
                     "self.processing_thread is populated!")

        self.setup_subscriptions()
182032
public static ServerConnector createSocketConnector(Server server, String host, int port) {
        Assert.notNull(server, "'server' must not be null");
        Assert.notNull(host, "'host' must not be null");

        HttpConnectionFactory httpConnectionFactory = createHttpConnectionFactory();
        ServerConnector connector = new ServerConnector(server, httpConnectionFactory);
        initializeConnector(connector, host, port);
        return connector;
    }
1115209
def connect(self):
        """"""
        if self.state is ConnectionStates.DISCONNECTED and not self.blacked_out():
            self.last_attempt = time.time()
            next_lookup = self._next_afi_sockaddr()
            if not next_lookup:
                self.close(Errors.KafkaConnectionError('DNS failure'))
                return self.state
            else:
                log.debug('%s: creating new socket', self)
                assert self._sock is None
                self._sock_afi, self._sock_addr = next_lookup
                self._sock = socket.socket(self._sock_afi, socket.SOCK_STREAM)

            for option in self.config['socket_options']:
                log.debug('%s: setting socket option %s', self, option)
                self._sock.setsockopt(*option)

            self._sock.setblocking(False)
            self.state = ConnectionStates.CONNECTING
            self.config['state_change_callback'](self.node_id, self._sock, self)
            log.info('%s: connecting to %s:%d [%s %s]', self, self.host,
                     self.port, self._sock_addr, AFI_NAMES[self._sock_afi])

        if self.state is ConnectionStates.CONNECTING:
            # in non-blocking mode, use repeated calls to socket.connect_ex
            # to check connection status
            ret = None
            try:
                ret = self._sock.connect_ex(self._sock_addr)
            except socket.error as err:
                ret = err.errno

            # Connection succeeded
            if not ret or ret == errno.EISCONN:
                log.debug('%s: established TCP connection', self)

                if self.config['security_protocol'] in ('SSL', 'SASL_SSL'):
                    log.debug('%s: initiating SSL handshake', self)
                    self.state = ConnectionStates.HANDSHAKE
                    self.config['state_change_callback'](self.node_id, self._sock, self)
                    # _wrap_ssl can alter the connection state -- disconnects on failure
                    self._wrap_ssl()

                elif self.config['security_protocol'] == 'SASL_PLAINTEXT':
                    log.debug('%s: initiating SASL authentication', self)
                    self.state = ConnectionStates.AUTHENTICATING
                    self.config['state_change_callback'](self.node_id, self._sock, self)

                else:
                    # security_protocol PLAINTEXT
                    log.info('%s: Connection complete.', self)
                    self.state = ConnectionStates.CONNECTED
                    self._reset_reconnect_backoff()
                    self.config['state_change_callback'](self.node_id, self._sock, self)

            # Connection failed
            # WSAEINVAL == 10022, but errno.WSAEINVAL is not available on non-win systems
            elif ret not in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK, 10022):
                log.error('Connect attempt to %s returned error %s.'
                          ' Disconnecting.', self, ret)
                errstr = errno.errorcode.get(ret, 'UNKNOWN')
                self.close(Errors.KafkaConnectionError('{} {}'.format(ret, errstr)))
                return self.state

            # Needs retry
            else:
                pass

        if self.state is ConnectionStates.HANDSHAKE:
            if self._try_handshake():
                log.debug('%s: completed SSL handshake.', self)
                if self.config['security_protocol'] == 'SASL_SSL':
                    log.debug('%s: initiating SASL authentication', self)
                    self.state = ConnectionStates.AUTHENTICATING
                else:
                    log.info('%s: Connection complete.', self)
                    self.state = ConnectionStates.CONNECTED
                    self._reset_reconnect_backoff()
                self.config['state_change_callback'](self.node_id, self._sock, self)

        if self.state is ConnectionStates.AUTHENTICATING:
            assert self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL')
            if self._try_authenticate():
                # _try_authenticate has side-effects: possibly disconnected on socket errors
                if self.state is ConnectionStates.AUTHENTICATING:
                    log.info('%s: Connection complete.', self)
                    self.state = ConnectionStates.CONNECTED
                    self._reset_reconnect_backoff()
                    self.config['state_change_callback'](self.node_id, self._sock, self)

        if self.state not in (ConnectionStates.CONNECTED,
                              ConnectionStates.DISCONNECTED):
            # Connection timed out
            request_timeout = self.config['request_timeout_ms'] / 1000.0
            if time.time() > request_timeout + self.last_attempt:
                log.error('Connection attempt to %s timed out', self)
                self.close(Errors.KafkaConnectionError('timeout'))
                return self.state

        return self.state
121921
def connect(self, url=c.LOCALHOST, port=None, timeout=c.INITIAL_TIMEOUT,
                      debug=False):
        """"""
        if port != None: # force a selection to a new port
            if self._port!=None: # if previously allocated port, return it
                portpicker.return_port(self._port)
            self._port = port
        elif self._port==None: # no connection exists
            self._port = portpicker.pick_unused_port()
        self._url = url
        if ":" in url and not url.startswith("["):  # Support ipv6 addresses.
            url = "[%s]" % url
        for i in range(timeout):
            startTime = time.time()
            if debug:
                print("attempt #%d to websocket connect to %s:%s"%(i, url, port))
            try:
                finalUrl = "ws://%s:%s/sc2api" %(url, self._port)
                ws = websocket.create_connection(finalUrl, timeout=timeout)
                #print("ws:", ws)
                self._client = protocol.StarcraftProtocol(ws)
                #super(ClientController, self).__init__(client) # ensure RemoteController initializtion is performed
                #if self.ping(): print("init ping()") # ensure the latest state is synced
                # ping returns:
                #   game_version:   "4.1.2.60604"
                #   data_version:   "33D9FE28909573253B7FC352CE7AEA40"
                #   data_build:     60604
                #   base_build:     60321
                return self
            except socket.error: pass  # SC2 hasn't started listening yet.
            except websocket.WebSocketException as err:
                print(err, type(err))
                if "Handshake Status 404" in str(err):
                    pass  # SC2 is listening, but hasn't set up the /sc2api endpoint yet.
                else: raise
            except Exception as e:
                print(type(e), e)
            sleepTime = max(0, 1 - (time.time() - startTime)) # try to wait for up to 1 second total
            if sleepTime:   time.sleep(sleepTime)
        raise websocket.WebSocketException("Could not connect to game at %s on port %s"%(url, port))
833828
protected synchronized void connect()
    {
        if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
            api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
        if (shutdown)
            throw new RejectedExecutionException("JDA is shutdown!");
        initiating = true;

        String url = api.getGatewayUrl() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
        if (compression)
        {
            url += "&compress=zlib-stream";
            decompressBuffer = newDecompressBuffer();
        }

        try
        {
            socket = api.getWebSocketFactory()
                    .createSocket(url)
                    .addHeader("Accept-Encoding", "gzip")
                    .addListener(this);
            socket.connect();
        }
        catch (IOException | WebSocketException e)
        {
            api.resetGatewayUrl();
            //Completely fail here. We couldn't make the connection.
            throw new IllegalStateException(e);
        }
    }
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);
        }
    }
155307
public static WebsocketServerTransport create(int port) {
    HttpServer httpServer = HttpServer.create().port(port);
    return create(httpServer);
  }