This just creates the websocket connection
420211
def connect(self,soft_reset=False,**options):
        
        self._state = STATE_CONNECTING
        logger.debug("About to connect to {}".format(self.url))

        m = re.search('(ws+)://([\w\.]+)(:?:(\d+))?',self.url)

        options['subprotocols'] = ['wamp.2.json']
        options['enable_multithread'] = True
        options.setdefault('timeout',self._loop_timeout)

        # Handle the weird issue in websocket that the origin
        # port will be always http://host:port even though connection is
        # wss. This causes some origin issues with demo.crossbar.io demo
        # so we ensure we use http or https appropriately depending on the
        # ws or wss protocol
        if m and m.group(1).lower() == 'wss':
            origin_port = ':'+m.group(3) if m.group(3) else ''
            options['origin'] = u'https://{}{}'.format(m.group(2),origin_port)

        # Attempt connection once unless it's autoreconnect in which
        # case we try and try again...
        while True:
            try:
                if self.sslopt:
                    options.setdefault('sslopt',self.sslopt)

                # By default if no settings are chosen we apply
                # the looser traditional policy (makes life less
                # secure but less excruciating on windows)
                if options.get('sslopt') is None:
                    options['sslopt'] = {
                        "cert_reqs":ssl.CERT_NONE,
                        "check_hostname": False
                    }

                if self.sockopt:
                    options.setdefault('sockopt',self.sockopt)

                self.ws = websocket.create_connection(
                                self.url,
                                **options
                            )
                self.handle_connect()
            except Exception as ex:
                if self.auto_reconnect:
                    logger.debug(
                        "Error connecting to {url}. Reconnection attempt in {retry} second(s). {err}".format(
                            url=self.url,
                            retry=self.auto_reconnect,
                            err=ex
                        )
                    )
                    time.sleep(self.auto_reconnect)
                    continue
                else:
                    raise
            break

        logger.debug("Connected to {}".format(self.url))
        if not soft_reset:
            self._subscriptions    = {}
            self._registered_calls = {}
        self._requests_pending = {}
        self._state = STATE_WEBSOCKET_CONNECTED

        # notify the threading.Conditional that restart can happen
        self._request_loop_notify_restart.acquire()
        self._request_loop_notify_restart.notify()
        self._request_loop_notify_restart.release()
36174
private WebSocketInputStream openInputStream(Socket socket) throws WebSocketException
    {
        try
        {
            // Get the input stream of the raw socket through which
            // this client receives data from the server.
            return new WebSocketInputStream(
                new BufferedInputStream(socket.getInputStream()));
        }
        catch (IOException e)
        {
            // Failed to get the input stream of the raw socket.
            throw new WebSocketException(
                WebSocketError.SOCKET_INPUT_STREAM_FAILURE,
                "Failed to get the input stream of the raw socket: " + e.getMessage(), e);
        }
    }
360418
public void onModuleLoad() {
    final Button sendButton = new Button("Send");
    final TextBox nameField = new TextBox();
    nameField.setText("GWT User");
    final Label errorLabel = new Label();
    
    final Label outputLabel = new Label();
    
    final Element output = DOM.getElementById("output");
    final Element status = DOM.getElementById("status");

    final Console console = new Console();


    console.log("adding websocket");
    
    // Establish a websocket communication channel to the atmosphere chat service.
    // Websocket socket = new Websocket("ws://localhost:8080/chat?X-Atmosphere-tracking-id=5ebed4c5-0b90-4166-88b2-9f273719ab75&X-Atmosphere-Framework=2.2.1-jquery&X-Atmosphere-Transport=websocket&Content-Type=application/json&X-atmo-protocol=true");
    final String url = "ws://localhost:8080/stream";
    Websocket socket = new Websocket(url);
    
    socket.addListener(new WebsocketListener() {

        @Override
        public void onClose() {
    	    // do something on close
        }

        @Override
        public void onMessage(String msg) {
	        // a message is received
        	console.log("onMessage(): " + msg);
        	outputLabel.setText("websocket " + url + ": " + msg);
        	output.setInnerText(msg);
        }

        @Override
        public void onOpen() {
	        // do something on open
        	console.log("onOpen()");
        	status.setInnerText("connected: " + url);
        }
    });
    
    socket.open();
    
    console.log("websocket is open");
    
  }
1038318
def connection_made(self, transport: asyncio.BaseTransport) -> None:
        
        super().connection_made(transport)
        # Register the connection with the server before creating the handler
        # task. Registering at the beginning of the handler coroutine would
        # create a race condition between the creation of the task, which
        # schedules its execution, and the moment the handler starts running.
        self.ws_server.register(self)
        self.handler_task = self.loop.create_task(self.handler())
1108036
def _create_socket(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s = ssl.wrap_socket(s)
        s.connect((self.host, self.__port))
        s.settimeout(self.timeout)
        return s
59047
function Connection(options) {
	
	if (!(this instanceof Connection)){
		return new Connection(options);
	}
	
	
	this.prefixCounter = 0;
	this.serverMessages = {};
	this._options = {
		username: options.username || options.user || '',
		password: options.password || '',
		host: options.host || 'localhost',
		port: options.port || 143,
		secure: options.secure === true ? { // secure = true means default behavior
			rejectUnauthorized: false // Force pre-node-0.9.2 behavior
		} : (options.secure || false),
		timeout: options.timeout || 10000, // connection timeout in msecs
		xoauth: options.xoauth,
		xoauth2: options.xoauth2
	};
	
	this._messages = {};
	this._messages = {};
	
	if (options.debug===true){
		this.debug = function(msg){
			console.log(msg);
		}
	}
	
		
	if (options.chainDebug===true){
		this.chainDebug = function(msg){
			console.log(msg);
		}
	}
	
	this.socket = null;
	
	this._messages_prefix_key={};
	this._messages_key_prefix={};
	this._messages={};
	
	
	this._msg_buffer = '';
	this._resetChainCommands();
}
1093573
function Connection(ws, logger) {
        events.EventEmitter.call(this);

        this._ws = ws;
        this._logger = logger;
        this._connected = true;

        this._ws.on("message", this._receive.bind(this));
        this._ws.once("close", this.close.bind(this));
    }
1374250
private function initWebsocketServer()
    {
        $websocketBind = $this->sandstoneApplication['sandstone.websocket.server']['bind'];
        $websocketPort = $this->sandstoneApplication['sandstone.websocket.server']['port'];

        $socket = new ReactSocketServer("$websocketBind:$websocketPort", $this->loop);

        new IoServer(
            new HttpServer(
                new WsServer(
                    new ServerProtocol(
                        new WebsocketApplication(
                            $this->sandstoneApplication
                        )
                    )
                )
            ),
            $socket
        );
    }
549596
def connection_open(self) -> None:
        
        # 4.1. The WebSocket Connection is Established.
        assert self.state is State.CONNECTING
        self.state = State.OPEN
        logger.debug("%s - state = OPEN", self.side)
        # Start the task that receives incoming WebSocket messages.
        self.transfer_data_task = self.loop.create_task(self.transfer_data())
        # Start the task that sends pings at regular intervals.
        self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping())
        # Start the task that eventually closes the TCP connection.
        self.close_connection_task = self.loop.create_task(self.close_connection())
1255515
protected function connectWs()
    {
        $this->logger->info('starting connection to websocket', ['gateway' => $this->gateway]);

        $this->wsFactory->__invoke($this->gateway)->then(
            [$this, 'handleWsConnection'],
            [$this, 'handleWsError']
        );
    }
750797
@PostConstruct
    protected void startRTMAndWebSocketConnection() {
        slackService.connectRTM(getSlackToken());
        if (slackService.getWebSocketUrl() != null) {
            webSocketManager = new WebSocketConnectionManager(client(), handler(), slackService.getWebSocketUrl());
            webSocketManager.start();
        } else {
            logger.error("No web socket url returned by Slack.");
        }
    }
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()
324830
public void onOpen() {
    LOGGER.d("webSocket established...");
    connectionEstablished = true;
    retryConnectionCount = 0;
    for (AVConnectionListener listener: connectionListeners.values()) {
      listener.onWebSocketOpen();
    }

    resetConnectingStatus(true);

    // auto send login packet.
    LoginPacket lp = new LoginPacket();
    lp.setAppId(AVOSCloud.getApplicationId());
    lp.setInstallationId(AVInstallation.getCurrentInstallation().getInstallationId());
    this.sendPacket(lp);
  }
935990
function WebSocket(url, opt_protocols) {
    var scope = ctorEvent();
    goog.base(this, descriptor);

    /**
     * Underlying WS.
     * @type {!WebSocket}
     * @private
     */
    this.handle_ = arguments.length == 1 ?
        new originalWs(url) :
        new originalWs(url, opt_protocols);

    /**
     * Event type trackers, by name.
     * @type {!Object.<Function>}
     * @private
     */
    this.trackers_ = {};

    /**
     * Properties, accumulated during setup before send().
     * @type {!Object}
     * @private
     */
    this.props_ = {
      'url': url,
      'protocol': opt_protocols
    };

    wtf.trace.Scope.leave(scope);
  }
568625
function() {
      var t = this, hostName = t.get('hostName'), hostPort = t.get('hostPort'),
      url = t.get('url');

      // Build the URL if not specified
      if (!url) {
        url = t.attributes.url = 'http://' + hostName + ':' + hostPort;
        t.set('url', url);
      }

      // Connect with this url
      var opts = {
        // 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'],
        'force new connection': true,      // Don't re-use existing connections
        'reconnect': false                 // Don't let socket.io reconnect.
                                           // Reconnects are performed by the Router.
      };
      var socket = SocketIO.connect(url, opts);
      t.set({socket:socket}).bindConnectionEvents();
    }
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();
    }
1042851
function Channel_connect(cb) {
  cb = utils.callOnce(cb)

  var wsClient = new websocket.client()

  wsClient.addListener("connect",       onConnect)
  wsClient.addListener("connectFailed", onConnectFailed)

  wsClient.connect(this._url, [this._protocol])

  var channel = this

  //-----------------------------------
  function onConnect(wsConn) {
    channel._wsConn = wsConn

    wsConn.addListener("message", onMessage)
    wsConn.addListener("close",   onClose)
    wsConn.addListener("error",   onError)

    cb(null)
  }

  //-----------------------------------
  function onConnectFailed(err) {
    cb(err)
  }

  //-----------------------------------
  function onMessage(message) {
    if (!channel._wsConn) return
    if (message.type != "utf8") return

    message = JSON.parse(message.utf8Data)
    DEBUGMSG("onMessage", utils.JL(message))

    channel.emit("message", message)
  }

  //-----------------------------------
  function onClose() {
    if (!channel._wsConn) return

    channel._wsConn = null
    channel.emit("close")
  }

  //-----------------------------------
  function onError(err) {
    channel.emit("error", err)
  }
}