Connect to websocket through asyncio http interface
423464
def connect(self, username, checksum, password=None, key=None):
        """"""

        ws_url = (
            f"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}"
            f"&rn={random_id(6)}&t={int(time.time() * 1000)}&transport=websocket&EIO=3"
        )
        if password:
            ws_url += f"&password={password}"
        elif key:
            ws_url += f"&key={key}"

        ARBITRATOR.create_connection(
            self.proto, ws_url, self.headers["User-Agent"], self.cookies
        )
        self.__conn_barrier.wait()
1197627
async def running(self):
        """"""
        try:
            async with self._session.ws_connect(self._url) as ws:
                self.state = STATE_RUNNING
                async for msg in ws:
                    if msg.type == aiohttp.WSMsgType.TEXT:
                        ensure_future(self._async_callback(
                            json.loads(msg.data)))
                        _LOGGER.debug('Websocket data: %s', msg.data)
                    elif msg.type == aiohttp.WSMsgType.CLOSED:
                        break
                    elif msg.type == aiohttp.WSMsgType.ERROR:
                        break
        except aiohttp.ClientConnectorError:
            if self.state != STATE_STOPPED:
                self.retry()
        except Exception as err:
            _LOGGER.error('Unexpected error %s', err)
            if self.state != STATE_STOPPED:
                self.retry()
        else:
            if self.state != STATE_STOPPED:
                self.retry()
610954
async def from_client(cls, client, *, resume=False):
        """"""
        gateway = 'wss://' + client.endpoint + '/?v=4'
        ws = await websockets.connect(gateway, loop=client.loop, klass=cls, compression=None)
        ws.gateway = gateway
        ws._connection = client
        ws._max_heartbeat_timeout = 60.0

        if resume:
            await ws.resume()
        else:
            await ws.identify()

        return ws
543465
async def create_websocket(url: str,
                           ssl: Optional[SSLContext] = None,
                           headers: Optional[list] = None,
                           subprotocols: Optional[list] = None):
    
    url = yarl.URL(url)
    args = {}
    if headers:
        args["headers"] = headers

    # automatically use ssl if it's websocket secure
    if ssl is None:
        ssl = url.scheme == "wss"
    if ssl:
        if ssl is True:
            ssl = SSLContext()
        args["ssl_context"] = ssl
        args["autostart_tls"] = True
        args["tls_standard_compatible"] = False

    addr = (url.host, int(url.port))
    ws = Websocket()
    await ws.__ainit__(
        addr=addr, path=url.path_qs, subprotocols=subprotocols, **args)
    return ws
963314
def run(self):
        

        server_logger = logging.getLogger('aiohttp.server')
        # In debug mode we don't use the standard request log but a more complete in response.py
        if log.getEffectiveLevel() == logging.DEBUG:
            server_logger.setLevel(logging.CRITICAL)

        logger = logging.getLogger("asyncio")
        logger.setLevel(logging.ERROR)

        if sys.platform.startswith("win"):
            loop = asyncio.get_event_loop()
            # Add a periodic callback to give a chance to process signals on Windows
            # because asyncio.add_signal_handler() is not supported yet on that platform
            # otherwise the loop runs outside of signal module's ability to trap signals.

            def wakeup():
                loop.call_later(0.5, wakeup)
            loop.call_later(0.5, wakeup)

        server_config = Config.instance().get_section_config("Server")

        ssl_context = None
        if server_config.getboolean("ssl"):
            if sys.platform.startswith("win"):
                log.critical("SSL mode is not supported on Windows")
                raise SystemExit
            ssl_context = self._create_ssl_context(server_config)

        self._loop = asyncio.get_event_loop()

        if log.getEffectiveLevel() == logging.DEBUG:
            # On debug version we enable info that
            # coroutine is not called in a way await/yield from
            self._loop.set_debug(True)

        for key, val in os.environ.items():
            log.debug("ENV %s=%s", key, val)

        self._app = aiohttp.web.Application()
        # Background task started with the server
        self._app.on_startup.append(self._on_startup)

        # Allow CORS for this domains
        cors = aiohttp_cors.setup(self._app, defaults={
            # Default web server for web gui dev
            "http://127.0.0.1:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://localhost:8080": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://127.0.0.1:4200": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://localhost:4200": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "http://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*"),
            "https://gns3.github.io": aiohttp_cors.ResourceOptions(expose_headers="*", allow_headers="*")
        })

        PortManager.instance().console_host = self._host

        for method, route, handler in Route.get_routes():
            log.debug("Adding route: {} {}".format(method, route))
            cors.add(self._app.router.add_route(method, route, handler))
        for module in MODULES:
            log.debug("Loading module {}".format(module.__name__))
            m = module.instance()
            m.port_manager = PortManager.instance()

        log.info("Starting server on {}:{}".format(self._host, self._port))

        self._handler = self._app.make_handler()
        if self._run_application(self._handler, ssl_context) is False:
            self._loop.stop()
            return

        self._signal_handling()
        self._exit_handling()

        if server_config.getboolean("shell"):
            asyncio.async(self.start_shell())

        try:
            self._loop.run_forever()
        except TypeError as e:
            # This is to ignore an asyncio.windows_events exception
            # on Windows when the process gets the SIGBREAK signal
            # TypeError: async() takes 1 positional argument but 3 were given
            log.warning("TypeError exception in the loop {}".format(e))
        finally:
            if self._loop.is_running():
                self._loop.run_until_complete(self.shutdown_server())
59378
def serve_websocket(request, port):
    """"""
    env = request.environ

    # Send HTTP response 101 Switch Protocol downstream
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))

    # Map the websocket URL to the upstream localhost:4000x Notebook instance
    parts = urlparse(request.url)
    parts = parts._replace(scheme="ws", netloc="localhost:{}".format(port))
    url = urlunparse(parts)

    # Proxy initial connection headers
    headers = [(header, value) for header, value in request.headers.items() if header.lower() in CAPTURE_CONNECT_HEADERS]

    logger.info("Connecting to upstream websockets: %s, headers: %s", url, headers)

    ws = ProxyClient(url, headers=headers)
    ws.connect()

    # TODO: Will complain loudly about already send headers - how to abort?
    return httpexceptions.HTTPOk()
651779
def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # handle known errors, will reconnect
      on_close(exc.code, exc.reason)

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect
      on_close(1006, exc.message)

    rescue => exc
      # TODO: crash instead of reconnecting on unknown errors?
      error exc
      on_close(1006, exc.message)

    else
      # client closed, not going to happen
      on_close(ws.close_code, ws.close_reason)

    ensure
      @ws = nil

      ws.disconnect
    end
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();
    }
380097
def websocket(
        self, uri, host=None, strict_slashes=None, subprotocols=None, name=None
    ):
        
        self.enable_websocket()

        # Fix case where the user did not prefix the URL with a /
        # and will probably get confused as to why it's not working
        if not uri.startswith("/"):
            uri = "/" + uri

        if strict_slashes is None:
            strict_slashes = self.strict_slashes

        def response(handler):
            async def websocket_handler(request, *args, **kwargs):
                request.app = self
                if not getattr(handler, "__blueprintname__", False):
                    request.endpoint = handler.__name__
                else:
                    request.endpoint = (
                        getattr(handler, "__blueprintname__", "")
                        + handler.__name__
                    )
                try:
                    protocol = request.transport.get_protocol()
                except AttributeError:
                    # On Python3.5 the Transport classes in asyncio do not
                    # have a get_protocol() method as in uvloop
                    protocol = request.transport._protocol
                ws = await protocol.websocket_handshake(request, subprotocols)

                # schedule the application handler
                # its future is kept in self.websocket_tasks in case it
                # needs to be cancelled due to the server being stopped
                fut = ensure_future(handler(request, ws, *args, **kwargs))
                self.websocket_tasks.add(fut)
                try:
                    await fut
                except (CancelledError, ConnectionClosed):
                    pass
                finally:
                    self.websocket_tasks.remove(fut)
                await ws.close()

            self.router.add(
                uri=uri,
                handler=websocket_handler,
                methods=frozenset({"GET"}),
                host=host,
                strict_slashes=strict_slashes,
                name=name,
            )
            return handler

        return response
420021
function WebsocketConnection(socket, url) {
  this.socket = socket;
  this.url = url;

  this.deferreds = {};
  this.nextRequestId = 0;

  this.onReply = this.onReply.bind(this);
  this.onEvent = this.onEvent.bind(this);
}
1322055
async def socket_connection(self):
        
        if not self._registered:
            _LOGGER.error('Client not registered, cannot start socket.')
            return

        url = '{}?DeviceID={}&api_key={}'.format(
            self.construct_url(SOCKET_URL), self._api_id, self._api_key)

        fail_count = 0
        while True:
            _LOGGER.debug('Attempting Socket Connection.')
            try:
                with async_timeout.timeout(DEFAULT_TIMEOUT,
                                           loop=self._event_loop):
                    self.wsck = await self._api_session.ws_connect(url)

                # Enable sever session updates:
                try:
                    msg = await self.wsck.send_str(
                        '{"MessageType":"SessionsStart", "Data": "0,1500"}')
                except Exception as err:
                    # Catch all for now
                    _LOGGER.error('Failure setting session updates: %s', err)
                    raise ValueError('Session updates error.')

                _LOGGER.debug('Socket Connected!')
                fail_count = 0
                while True:
                    msg = await self.wsck.receive()
                    if msg.type == aiohttp.WSMsgType.text:
                        # Process data
                        self.process_msg(msg.data)

                    elif msg.type == aiohttp.WSMsgType.closed:
                        raise ValueError('Websocket was closed.')
                    elif msg.type == aiohttp.WSMsgType.error:
                        _LOGGER.debug(
                            'Websocket encountered an error: %s', msg)
                        raise ValueError('Websocket error.')

            except (aiohttp.ClientError, asyncio.TimeoutError,
                    aiohttp.WSServerHandshakeError,
                    ConnectionRefusedError, OSError, ValueError) as err:
                if not self._shutdown:
                    fail_count += 1
                    _LOGGER.debug('Websocket unintentionally closed.'
                                  ' Trying reconnect in %ss. Error: %s',
                                  (fail_count * 5) + 5, err)
                    await asyncio.sleep(15, self._event_loop)
                    continue
                else:
                    break
171360
function wsConnect() {

            var typeOfConnection;

            if (location.protocol === 'https:') {
                typeOfConnection = 'wss';
            } else {
                typeOfConnection = 'ws'
            }

            self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);

            self.ws.onopen = function (event) {

                //send an intial message to server and prove that the connection is built.
                self.send('connected', 'WSM: Browser confirms websocket connection.')

                reactive(self);

            };

            self.ws.onmessage = function (event) {
                // flags.binary will be set if a binary data is received.
                // flags.masked will be set if the data was masked.
                //console.log(event.data);

                self.processMessage(JSON.parse(event.data));
            };

            self.ws.onclose = function (event) {

                wsConnect();
            }
        }
810355
def _connect(self, endpoint: str):
        
        if self._socket:
            raise RuntimeError('Cannot run multiple Servers on the same socket')

        context = zmq.asyncio.Context()
        self._socket = context.socket(zmq.ROUTER)
        self._socket.bind(endpoint)

        _log.info("Starting server, listening on endpoint {}".format(endpoint))
744633
def connect(endpoint)
      rc = ffi_delegate.connect("%s", :string, endpoint)
      raise ArgumentError, "incorrect endpoint: %p" % endpoint if rc == -1
    end
434824
def websocket_handler(request):
    """"""

    logger.debug('New websocket connection.')
    websocket = web.WebSocketResponse()
    yield from websocket.prepare(request)
    uuid = uuid4()
    request.app['dispatcher'].subscribe(uuid, websocket)

    while True:
        # Consume input buffer
        try:
            msg = yield from websocket.receive()
        except RuntimeError as e:
            logger.debug('Websocket exception: %s', str(e))
            break
        except CancelledError:
            logger.debug('Websocket closed')
            break
        if msg.type == aiohttp.WSMsgType.CLOSED:
            logger.debug('Websocket closed')
            break
        elif msg.type == aiohttp.WSMsgType.ERROR:
            logger.debug('Websocket exception: %s', websocket.exception())
            break

    request.app['dispatcher'].unsubscribe(uuid)
    return websocket
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))
761287
async def enable_events(self) -> asyncio.Task:
        """"""
        return await self._connection.ws_connect(
            on_message=self._ws_on_message, on_error=self._ws_on_error
        )