Python websockets.ConnectionClosed() Examples

The following are 30 code examples of websockets.ConnectionClosed(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module websockets , or try the search function .
Example #1
Source Project: saltyrtc-server-python   Author: saltyrtc   File: protocol.py    License: MIT License 6 votes vote down vote up
def send(self, message: OutgoingMessageMixin) -> None:
        """
        Disconnected
        MessageError
        MessageFlowError
        """
        # Pack
        self.log.debug('Packing message: {}', message.type)
        data = message.pack(self)
        self.log.trace('server >> {}', message)

        # Send data
        self.log.debug('Sending message')
        try:
            await self._connection.send(data)
        except websockets.ConnectionClosed as exc:
            self.log.debug('Connection closed while sending')
            disconnected = Disconnected(exc.code)
            self.jobs.close(Result(disconnected))
            raise disconnected from exc 
Example #2
Source Project: saltyrtc-server-python   Author: saltyrtc   File: test_protocol.py    License: MIT License 6 votes vote down vote up
def test_explicit_permanent_key_unavailable(
            self, server_no_key, server, client_factory
    ):
        """
        Check that the server rejects a permanent key if the server
        has none.
        """
        key = libnacl.public.SecretKey()

        # Expect invalid key
        with pytest.raises(websockets.ConnectionClosed) as exc_info:
            await client_factory(
                server=server_no_key, permanent_key=key.pk, explicit_permanent_key=True,
                initiator_handshake=True)
        assert exc_info.value.code == CloseCode.invalid_key
        await server.wait_connections_closed() 
Example #3
Source Project: python-libjuju   Author: juju   File: model.py    License: Apache License 2.0 6 votes vote down vote up
def block_until(self, *conditions, timeout=None, wait_period=0.5):
        """Return only after all conditions are true.

        Raises `websockets.ConnectionClosed` if disconnected.
        """
        def _disconnected():
            return not (self.is_connected() and self.connection().is_open)

        def done():
            return _disconnected() or all(c() for c in conditions)

        await utils.block_until(done,
                                timeout=timeout,
                                wait_period=wait_period,
                                loop=self.loop)
        if _disconnected():
            raise websockets.ConnectionClosed(1006, 'no reason') 
Example #4
Source Project: obs-ws-rc   Author: KirillMysnik   File: client.py    License: MIT License 6 votes vote down vote up
def _recv_loop(self):
        self._done_event.clear()

        while not self._ws_close_event.is_set():
            try:
                data = json.loads(await self._ws.recv())
            except websockets.ConnectionClosed:
                await self._close()

            else:
                message_id = data.get('message-id')
                if message_id is not None:
                    self._message_map.pop(message_id).set_result(data)
                    continue

                type_name = data.get('update-type')
                if type_name is not None:
                    asyncio.ensure_future(
                        self._handle_event(type_name, data), loop=self._loop)

                    continue

                # TODO: Not a response nor an event - log an error maybe?

        self._done_event.set() 
Example #5
Source Project: TwitchIO   Author: TwitchIO   File: websocket.py    License: MIT License 6 votes vote down vote up
def _listen(self):
        backoff = ExponentialBackoff()

        if not self.is_connected and self._last_exec:
            raise WSConnectionFailure(f'Websocket connection failure:\n\n{self._last_exec}')

        while True:
            if self._authentication_error:
                log.error('AUTHENTICATION ERROR:: Incorrect IRC Token passed.')
                raise AuthenticationError

            try:
                data = await self._websocket.recv()
            except websockets.ConnectionClosed:
                retry = backoff.delay()
                log.info('Websocket closed: Retrying connection in %s seconds...', retry)

                await asyncio.sleep(retry)
                await self._connect()
                continue

            await self._dispatch('raw_data', data)

            _task = self.loop.create_task(self.process_data(data))
            _task.add_done_callback(functools.partial(self._task_callback, data)) 
Example #6
Source Project: TwitchIO   Author: TwitchIO   File: websocket.py    License: MIT License 6 votes vote down vote up
def listen(self):
        while True:
            try:
                data = json.loads(await self._websocket.recv())
                self.loop.create_task(self._pool.base._dispatch('raw_pubsub', data))
            except websockets.ConnectionClosed:
                return self.loop.create_task(self.reconnection())

            if data['type'] == 'PONG':
                log.debug('PubSub %s received PONG payload.', self.node)
                self._timeout.set()
            elif data['type'] == 'RECONNECT':
                log.debug('PubSub %s received RECONNECT payload... Attempting reconnection', self.node)
                self.loop.create_task(self.reconnection())

            # self.loop.create_task(self._pool.base._dispatch('pubsub', data)) 
Example #7
Source Project: trinity   Author: ethereum   File: ethstats_client.py    License: MIT License 6 votes vote down vote up
def recv_handler(self) -> None:
        while self.manager.is_running:
            try:
                json_string = await self.websocket.recv()
            except websockets.ConnectionClosed as e:
                self.logger.debug2("Connection closed: %s", e)
                self.manager.cancel()
                return

            try:
                message: EthstatsMessage = self.deserialize_message(str(json_string))
            except EthstatsException as e:
                self.logger.warning('Cannot parse message from server: %s' % e)
                return

            await self.recv_queue.put(message)

    # Get messages from queue, serialize them and send over websocket 
Example #8
Source Project: btc_bot_framework   Author: penta2019   File: websocket.py    License: MIT License 6 votes vote down vote up
def __worker(self):
        while True:
            try:
                self._on_init()

                async with websockets.connect(self.url) as ws:
                    self._ws = ws
                    self._on_open()
                    while True:
                        try:
                            msg = await ws.recv()
                            self._on_message(msg)
                        except websockets.ConnectionClosed:
                            break
                        except Exception as e:
                            self._on_error(e)

                self._on_close()
            except Exception:
                self.log.error(traceback.format_exc())

            self._ws = None
            if not self.running:
                break
            await asyncio.sleep(5) 
Example #9
Source Project: homematicip-rest-api   Author: coreGreenberet   File: connection.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _ws_ping_loop(self):
        try:
            while True:
                logger.debug("Sending out ping request.")
                pong_waiter = await self.socket_connection.ping()
                await asyncio.wait_for(pong_waiter, timeout=self.ping_timeout)
                logger.debug("Pong received.")
                await asyncio.sleep(self.ping_loop)
        except CancelledError:
            logger.debug("WS Ping pong task cancelled.")
        except (asyncio.TimeoutError, ConnectionClosed):
            logger.error("No Pong received from server.")
        except Exception as err:
            logger.debug("WS Ping pong task close.")
            logger.exception(err)
        finally:
            await self.close_websocket_connection() 
Example #10
Source Project: homematicip-rest-api   Author: coreGreenberet   File: connection.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _ws_loop(self, on_message, on_error):
        try:
            while True:
                msg = await self.socket_connection.recv()
                logger.debug("incoming hmip message")
                on_message(msg.decode())
        except TypeError:
            logger.error("Problem converting incoming bytes %s", msg)
        except ConnectionClosed:
            logger.debug("Connection closed by server")
        except CancelledError:
            logger.info("Reading task is cancelled.")
        except Exception as err:
            logger.debug("WS Reader task stop.")
            logger.exception(err)
        finally:
            await self.close_websocket_connection(source_is_reading_loop=True)
            await self._closing_task

            raise HmipConnectionError() 
Example #11
Source Project: JJMumbleBot   Author: DuckBoss   File: web_helper.py    License: GNU General Public License v3.0 5 votes vote down vote up
def send_message(websocket, path):
    web_tick_rate = float(global_settings.cfg[C_WEB_SETTINGS][P_WEB_TICK_RATE])
    try:
        while True:
            # web_data = monitor_service.get_hardware_info()
            # web_data.update(monitor_service.get_system_info())
            web_data = {"cur_time": str(datetime.now()).split('.')[0]}
            web_data.update({"bot_uptime": f'{check_up_time()}'})
            web_data.update(monitor_service.get_last_command_output())
            web_data.update(monitor_service.get_all_online())
            packed_data = json.dumps(web_data)
            await websocket.send(packed_data)
            await asyncio.sleep(web_tick_rate)
    except websockets.ConnectionClosed:
        return 
Example #12
Source Project: python-idex   Author: sammchardy   File: websockets.py    License: MIT License 5 votes vote down vote up
def _run(self):

        keep_waiting: bool = True

        async with ws.connect(self.STREAM_URL, ssl=True) as socket:
            self._socket = socket

            await self.handshake()
            try:
                while keep_waiting:
                    try:
                        evt = await asyncio.wait_for(self._socket.recv(), timeout=self.TIMEOUT)
                    except asyncio.TimeoutError:
                        self._log.debug("no message in {} seconds".format(self.TIMEOUT))
                        await self._socket.ping()
                    except asyncio.CancelledError:
                        self._log.debug("cancelled error")
                        await self._socket.ping()
                    else:
                        try:
                            evt_obj = json.loads(evt)
                        except ValueError:
                            pass
                        else:
                            await self._coro(evt_obj)

            except ws.ConnectionClosed as e:
                keep_waiting = False
                await self._reconnect()
            except Exception as e:
                self._log.debug('ws exception:{}'.format(e))
                keep_waiting = False
            #    await self._reconnect() 
Example #13
Source Project: conjure-up   Author: conjure-up   File: common.py    License: MIT License 5 votes vote down vote up
def do_deploy(msg_cb):
    await events.ModelConnected.wait()

    for step in app.steps:
        await step.before_deploy(msg_cb=msg_cb)
    events.PreDeployComplete.set()

    msg = 'Deploying Applications.'
    app.log.info(msg)
    msg_cb(msg)

    datetimestr = datetime.now().strftime("%Y%m%d.%H%m")
    fn = os.path.join(app.env['CONJURE_UP_CACHEDIR'],
                      '{}-deployed-{}.yaml'.format(
                          app.env['CONJURE_UP_SPELL'],
                          datetimestr))
    utils.spew(fn, app.current_bundle.to_yaml())
    for attempt in range(3):
        try:
            await app.juju.client.deploy(fn)
            break  # success
        except websockets.ConnectionClosed:
            if attempt == 2:
                raise
            await asyncio.sleep(1)

    events.DeploymentComplete.set() 
Example #14
Source Project: saltyrtc-server-python   Author: saltyrtc   File: protocol.py    License: MIT License 5 votes vote down vote up
def receive(self) -> IncomingMessageMixin:
        """
        Disconnected
        """
        # Safeguard
        # Note: This should never happen since the receive queue will
        #       be stopped when a client is being dropped.
        assert self.state < ClientState.dropped

        # Receive data
        try:
            data = await self._connection.recv()
        except websockets.ConnectionClosed as exc:
            self.log.debug('Connection closed while receiving')
            disconnected = Disconnected(exc.code)
            self.jobs.close(Result(disconnected))
            raise disconnected from exc
        self.log.debug('Received message')

        # Ensure binary
        if not isinstance(data, bytes):
            raise MessageError("Data must be 'bytes', not '{}'".format(type(data)))

        # Unpack data and return
        message = unpack(self, Packet(data))
        self.log.debug('Unpacked message: {}', message.type)
        self.log.trace('server << {}', message)
        return message 
Example #15
Source Project: saltyrtc-server-python   Author: saltyrtc   File: protocol.py    License: MIT License 5 votes vote down vote up
def ping(self) -> 'asyncio.Future[None]':
        """
        Disconnected
        """
        self.log.debug('Sending ping')
        try:
            pong_future = await self._connection.ping()
        except websockets.ConnectionClosed as exc:
            self.log.debug('Connection closed while pinging')
            disconnected = Disconnected(exc.code)
            self.jobs.close(Result(disconnected))
            raise disconnected from exc
        return cast('asyncio.Future[None]', pong_future) 
Example #16
Source Project: saltyrtc-server-python   Author: saltyrtc   File: protocol.py    License: MIT License 5 votes vote down vote up
def wait_pong(self, pong_future: 'asyncio.Future[None]') -> None:
        """
        Disconnected
        """
        self.log.debug('Waiting for pong')
        try:
            await pong_future
        except websockets.ConnectionClosed as exc:
            self.log.debug('Connection closed while waiting for pong')
            disconnected = Disconnected(exc.code)
            self.jobs.close(Result(disconnected))
            raise disconnected from exc 
Example #17
Source Project: saltyrtc-server-python   Author: saltyrtc   File: test_protocol.py    License: MIT License 5 votes vote down vote up
def test_path_full_lite(self, initiator_key, server, client_factory):
        """
        Add 253 fake responders to a path. Then, add a 254th responder
        and check that the correct error code (Path Full) is being
        returned.
        """
        assert len(server.protocols) == 0

        # Get path instance of server
        path = server.paths.get(initiator_key.pk)

        # Add fake clients to path
        clients = [_FakePathClient() for _ in range(0x02, 0x100)]
        for client in clients:
            path.add_pending(client)
        for client in clients:
            path.add_responder(client)

        # Now the path is full
        with pytest.raises(websockets.ConnectionClosed) as exc_info:
            await client_factory(responder_handshake=True)
        assert exc_info.value.code == CloseCode.path_full_error

        # Remove fake clients from path
        for client in clients:
            path.remove_client(client)
        await server.wait_connections_closed() 
Example #18
Source Project: saltyrtc-server-python   Author: saltyrtc   File: test_protocol.py    License: MIT License 5 votes vote down vote up
def test_explicit_invalid_permanent_key(
            self, server, client_factory
    ):
        """
        Check that the server rejects a permanent key it doesn't have.
        """
        key = libnacl.public.SecretKey()

        # Expect invalid key
        with pytest.raises(websockets.ConnectionClosed) as exc_info:
            await client_factory(
                permanent_key=key.pk, explicit_permanent_key=True,
                initiator_handshake=True)
        assert exc_info.value.code == CloseCode.invalid_key
        await server.wait_connections_closed() 
Example #19
Source Project: brave   Author: bbc   File: websockets_handler.py    License: Apache License 2.0 5 votes vote down vote up
def send_to_all_clients(self, messages_to_send):
        for msg in messages_to_send:
            for ws in self._websocket_clients:
                try:
                    await ws.send(json.dumps(msg))
                except websockets.ConnectionClosed:
                    self._websocket_clients.remove(ws) 
Example #20
Source Project: brave   Author: bbc   File: webrtc.py    License: Apache License 2.0 5 votes vote down vote up
def _send_data_to_all_peers(self, jsonData):
        for ws in self.peers:
            try:
                await ws.send(jsonData)
            except websockets.ConnectionClosed:
                pass 
Example #21
Source Project: python-libjuju   Author: juju   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _recv(self, request_id):
        if not self.is_open:
            raise websockets.exceptions.ConnectionClosed(0, 'websocket closed')
        return await self.messages.get(request_id) 
Example #22
Source Project: python-libjuju   Author: juju   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _receiver(self):
        try:
            while self.is_open:
                result = await utils.run_with_interrupt(
                    self.ws.recv(),
                    self.monitor.close_called,
                    loop=self.loop)
                if self.monitor.close_called.is_set():
                    break
                if result is not None:
                    result = json.loads(result)
                    await self.messages.put(result['request-id'], result)
        except CancelledError:
            pass
        except websockets.ConnectionClosed as e:
            log.warning('Receiver: Connection closed, reconnecting')
            await self.messages.put_all(e)
            # the reconnect has to be done as a task because the receiver will
            # be cancelled by the reconnect and we don't want the reconnect
            # to be aborted half-way through
            self.loop.create_task(self.reconnect())
            return
        except Exception as e:
            log.exception("Error in receiver")
            # make pending listeners aware of the error
            await self.messages.put_all(e)
            raise 
Example #23
Source Project: python-libjuju   Author: juju   File: connection.py    License: Apache License 2.0 5 votes vote down vote up
def _pinger(self):
        '''
        A Controller can time us out if we are silent for too long. This
        is especially true in JaaS, which has a fairly strict timeout.

        To prevent timing out, we send a ping every ten seconds.

        '''
        async def _do_ping():
            try:
                await pinger_facade.Ping()
                await asyncio.sleep(10, loop=self.loop)
            except CancelledError:
                pass

        pinger_facade = client.PingerFacade.from_connection(self)
        try:
            while True:
                await utils.run_with_interrupt(
                    _do_ping(),
                    self.monitor.close_called,
                    loop=self.loop)
                if self.monitor.close_called.is_set():
                    break
        except websockets.exceptions.ConnectionClosed:
            # The connection has closed - we can't do anything
            # more until the connection is restarted.
            log.debug('ping failed because of closed connection')
            pass 
Example #24
Source Project: rewrite   Author: initzx   File: node.py    License: GNU General Public License v3.0 5 votes vote down vote up
def listen(self):
        try:
            while self.ws.open:
                msg = await self.ws.recv()
                await self.on_message(json.loads(msg))
        except websockets.ConnectionClosed as e:
            await self.on_close(e.code, e.reason) 
Example #25
Source Project: wsstat   Author: Fitblip   File: test_coros.py    License: MIT License 5 votes vote down vote up
def mocked_websocket(*args, **kwargs):
        class MockedWebsocket(mock.Mock):
            def __init__(self, **kwargs):
                super().__init__(**kwargs)
                self.count = 0

            @asyncio.coroutine
            def recv(self, *args, **kwargs):
                self.count += 1
                if self.count > 3:
                    raise ConnectionClosed(1000, "Peace out homie!")
                return "Hello World!"

        return MockedWebsocket() 
Example #26
Source Project: python-binance-chain   Author: sammchardy   File: websockets.py    License: MIT License 5 votes vote down vote up
def _run(self):

        keep_waiting: bool = True

        logging.info(f"connecting to {self._get_ws_endpoint_url()}")
        try:
            async with ws.connect(self._get_ws_endpoint_url(), loop=self._loop) as socket:
                self._on_connect(socket)

                try:
                    while keep_waiting:
                        try:
                            evt = await asyncio.wait_for(self._socket.recv(), timeout=self._ping_timeout)
                        except asyncio.TimeoutError:
                            self._log.debug("no message in {} seconds".format(self._ping_timeout))
                            await self.send_keepalive()
                        except asyncio.CancelledError:
                            self._log.debug("cancelled error")
                            await self.ping()
                        else:
                            try:
                                evt_obj = json.loads(evt)
                            except ValueError:
                                pass
                            else:
                                await self._coro(evt_obj)
                except ws.ConnectionClosed as e:
                    self._log.debug('conn closed:{}'.format(e))
                    keep_waiting = False
                    await self._reconnect()
                except Exception as e:
                    self._log.debug('ws exception:{}'.format(e))
                    keep_waiting = False
                    await self._reconnect()
        except Exception as e:
            logging.info(f"websocket error: {e}") 
Example #27
Source Project: crypto-bot   Author: iilunin   File: BinanceWebsocket.py    License: Apache License 2.0 5 votes vote down vote up
def feature_finished(self, future: asyncio.Future, reconnect_fn=None, name=''):
        try:
            self.logInfo('Feature finished: "{}"'.format(name))

            if future.cancelled():
                return

            exc = future.exception()
            if exc:
                if (isinstance(exc, ConnectionClosed) and exc.code > 1002) \
                        or isinstance(exc, InvalidStatusCode, TypeError):
                    self.logError(exc)

                    if reconnect_fn and not self.stop:
                        self.logInfo('Trying to reconnect...')
                        sleep(1)
                        reconnect_fn()
                    else:
                        self.logInfo('No reconnection function...')
                    return
                else:
                    self.logError(exc)
            else:
                ws: WebSocketClientProtocol = future.result()

                if ws and ws.state == State.CLOSED:
                    self.logInfo('WS Closed: {} - {}'.format(ws.close_code, ws.close_reason))
        except:
            self.logError(traceback.format_exc()) 
Example #28
Source Project: meshcat-python   Author: rdeits   File: zmqrelay.py    License: MIT License 5 votes vote down vote up
def handle_new_connection(websocket, path):
    print("connected", websocket)
    my_queue = asyncio.Queue()
    queues.add(my_queue)
    try:
        while True:
            msg = await my_queue.get()
            await websocket.send(msg)
    except websockets.ConnectionClosed as e:
        queues.remove(queue) 
Example #29
Source Project: pollmaster   Author: matnad   File: bot.py    License: MIT License 5 votes vote down vote up
def websocket_loop(self):
        while True:
            try:
                msg = await self.websocket.recv()
            except websockets.ConnectionClosed as exc:
                if exc.code == 1000:
                    return
                raise
            data = json.loads(msg, encoding='utf-8')
            if self.eval_wait and data.get('response'):
                await self.responses.put(data)
            cmd = data.get('command')
            if not cmd:
                continue
            if cmd == 'ping':
                ret = {'response': 'pong'}
                self.log.info("received command [ping]")
            elif cmd == 'eval':
                self.log.info(f"received command [eval] ({data['content']})")
                content = data['content']
                data = await self.exec(content)
                ret = {'response': str(data)}
            else:
                ret = {'response': 'unknown command'}
            ret['author'] = self.cluster_name
            self.log.info(f"responding: {ret}")
            try:
                await self.websocket.send(json.dumps(ret).encode('utf-8'))
            except websockets.ConnectionClosed as exc:
                if exc.code == 1000:
                    return
                raise 
Example #30
Source Project: pollmaster   Author: matnad   File: bot.py    License: MIT License 5 votes vote down vote up
def ensure_ipc(self):
        self.websocket = w = await websockets.connect('ws://localhost:42069')
        await w.send(self.cluster_name.encode('utf-8'))
        try:
            await w.recv()
            self.ws_task = self.loop.create_task(self.websocket_loop())
            self.log.info("ws connection succeeded")
        except websockets.ConnectionClosed as exc:
            self.log.warning(f"! couldnt connect to ws: {exc.code} {exc.reason}")
            self.websocket = None
            raise