How to use the websockets.connect function in websockets

To help you get started, we’ve selected a few websockets examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pyrates / roll / tests / test_websockets_failure.py View on Github external
async def test_websocket_failure_receive(liveclient):

    @liveclient.app.route('/failure', protocol="websocket")
    async def failme(request, ws):
        raise NotImplementedError('OUCH')

    websocket = await websockets.connect(liveclient.wsl + '/failure')
    with pytest.raises(websockets.exceptions.ConnectionClosed):
        # Receiving, on the other hand, will raise immediatly an
        # error as the reader is closed. Only the writer is opened
        # as we are expected to send back the closing frame.
        await websocket.recv()

    await websocket.close()
    assert websocket.state == websockets.protocol.State.CLOSED
    assert websocket.close_code == 1011
    assert websocket.close_reason == 'Handler died prematurely.'
github udacity / udacidrone / udacidrone / connection / websocket_connection.py View on Github external
async def _dispatch_loop(self):
        """
        Continually listens to the drone connection for incoming messages.
        For each new message, decodes the MAVLink, creates messages as
        defined in `message_types.py`, and triggers all callbacks registered
        for that type of message.
        """
        last_msg_time = time.time()
        async with websockets.connect(self._uri) as ws:
            self._ws = ws
            while self._running:
                msg = await ws.recv()
                msg = self.decode_message(msg)

                if msg is None or msg.get_type() == 'BAD_DATA':
                    continue

                # send a heartbeat message back, since this needs to be
                # constantly sent so the autopilot knows this exists
                if msg.get_type() == 'HEARTBEAT':
                    # send -> type, autopilot, base mode, custom mode, system status
                    outmsg = self._mav.heartbeat_encode(mavutil.mavlink.MAV_TYPE_GCS,
                                                        mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0,
                                                        mavutil.mavlink.MAV_STATE_ACTIVE)
                    await self.send_message(outmsg)
github beerfactory / hbmqtt / hbmqtt / client.py View on Github external
kwargs['ssl'] = sc

        try:
            reader = None
            writer = None
            self._connected_state.clear()
            # Open connection
            if scheme in ('mqtt', 'mqtts'):
                conn_reader, conn_writer = \
                    yield from asyncio.open_connection(
                        self.session.remote_address,
                        self.session.remote_port, loop=self._loop, **kwargs)
                reader = StreamReaderAdapter(conn_reader)
                writer = StreamWriterAdapter(conn_writer)
            elif scheme in ('ws', 'wss'):
                websocket = yield from websockets.connect(
                    self.session.broker_uri,
                    subprotocols=['mqtt'],
                    loop=self._loop,
                    extra_headers=self.extra_headers,
                    **kwargs)
                reader = WebSocketsReader(websocket)
                writer = WebSocketsWriter(websocket)
            # Start MQTT protocol
            self._handler.attach(self.session, reader, writer)
            return_code = yield from self._handler.mqtt_connect()
            if return_code is not CONNECTION_ACCEPTED:
                self.session.transitions.disconnect()
                self.logger.warning("Connection rejected with code '%s'" % return_code)
                exc = ConnectException("Connection rejected by broker")
                exc.return_code = return_code
                raise exc
github krzynio / python-samsung-smarttv-2016 / sstv2016.py View on Github external
def _remote(keys, tv_addr,delay=1):
    websocket = yield from websockets.connect('ws://%s:%d/api/v2/channels/samsung.remote.control' % (tv_addr,8001))
    if type(keys) is str:
        _keys = [keys]
    else:
        _keys = keys

    try:
        while True:
            message = yield from websocket.recv()
            parsed = json.loads(message)
            if (parsed['event'] == 'ms.channel.connect'):  
                k = 0
                for key in _keys:
                    k = k + 1
                    cmd = '{"method":"ms.remote.control","params":{"Cmd":"Click","DataOfCmd":"%s","Option":"false","TypeOfRemote":"SendRemoteKey"}}' % key
                    yield from websocket.send(cmd)
                    if k != len(_keys):
github CoinAlpha / hummingbot / hummingbot / market / liquid / liquid_api_order_book_data_source.py View on Github external
async def listen_for_order_book_diffs(self, ev_loop: asyncio.BaseEventLoop, output: asyncio.Queue):
        """
        Subscribe to diff channel via web socket, and keep the connection open for incoming messages
        :param ev_loop: ev_loop to execute this function in
        :param output: an async queue where the incoming messages are stored
        """

        # {old_trading_pair: new_trading_pair}
        old_trading_pair_conversions = {}

        while True:
            try:
                trading_pairs: List[str] = await self.get_trading_pairs()

                async with websockets.connect(Constants.BAEE_WS_URL) as ws:
                    ws: websockets.WebSocketClientProtocol = ws
                    for trading_pair in trading_pairs:

                        old_trading_pair = trading_pair.replace('-', '')
                        old_trading_pair_conversions[old_trading_pair] = trading_pair

                        for side in [Constants.SIDE_BID, Constants.SIDE_ASK]:
                            subscribe_request: Dict[str, Any] = {
                                "event": Constants.WS_PUSHER_SUBSCRIBE_EVENT,
                                "data": {
                                    "channel": Constants.WS_ORDER_BOOK_DIFF_SUBSCRIPTION.format(
                                        currency_pair_code=old_trading_pair.lower(), side=side)
                                }
                            }

                            await ws.send(ujson.dumps(subscribe_request))
github Mausbiber / smartHome / clients / sh-client.py View on Github external
@asyncio.coroutine
def client_handler():
    # connect to server
    while True:
        try:
            websocket = yield from websockets.connect('ws://' + SERVER_IP + ':' + SERVER_CLIENTS_PORT + '/')
            break
        except OSError:
            pass
    # set up sending-queue
    task = asyncio.async(sending_loop(websocket))
    logger.debug('websockets .... asyncio.async')

    while True:

        # get message from client
        message_received = yield from websocket.recv()

        # leave if client is disconnect
        if message_received is None:
            logger.debug('Ben Client Handler Break....')
            break
github mikeyy / nonoCAPTCHA / nonocaptcha / speech.py View on Github external
async def get_text(self, mp3_filename):
        wav_filename = await mp3_to_wav(mp3_filename)
        conn_id = uuid4().hex
        url = (
            f"wss://speech.platform.bing.com/speech/recognition/dictation/cogn"
            f"itiveservices/v1?language=en-US&Ocp-Apim-Subscription-Key="
            f"{self.SUB_KEY}&X-ConnectionId={conn_id}&format=detailed"
        )
        async with websockets.connect(url) as websocket:
            await self.send_file(websocket, wav_filename)
            timeout = time.time() + 15
            while time.time() < timeout:
                response = await websocket.recv()
                content = await self.extract_json_body(response)
                if (
                    "RecognitionStatus" in content
                    and content["RecognitionStatus"] == "Success"
                ):
                    answer = content["NBest"][0]["Lexical"]
                    return answer
                if (
                    "RecognitionStatus" in content
                    and content["RecognitionStatus"] == "EndOfDictation"
                ):
                    return
github chuckus / chromewhip / chromewhip / chrome.py View on Github external
async def connect(self):
        self._ws = await websockets.connect(self._ws_uri, max_size=MAX_PAYLOAD_SIZE_BYTES)  # 16MB
        self._recv_task = asyncio.ensure_future(self.recv_handler())
        self._log.info('Connected to Chrome tab %s' % self._ws_uri)
github prawn-cake / vk-requests / vk_requests / streaming.py View on Github external
def worker(conn_url):
            extra_headers = {
                'Connection': 'upgrade',
                'Upgrade': 'websocket',
                'Sec-Websocket-Version': 13,
            }

            ws = yield from websockets.connect(
                conn_url, extra_headers=extra_headers)

            if ws is None:
                raise RuntimeError("Couldn't connect to the '%s'" % conn_url)

            try:
                while True:
                    message = yield from ws.recv()
                    yield from self._consumer_fn(message)
            finally:
                yield from ws.close()