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 File: connection.py    From homematicip-rest-api with 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 #2
Source File: protocol.py    From saltyrtc-server-python with 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 #3
Source File: connection.py    From homematicip-rest-api with 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 #4
Source File: websocket.py    From btc_bot_framework with 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 #5
Source File: client.py    From obs-ws-rc with 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 #6
Source File: test_protocol.py    From saltyrtc-server-python with 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 #7
Source File: ethstats_client.py    From trinity with 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 File: websocket.py    From TwitchIO with 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 #9
Source File: websocket.py    From TwitchIO with 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 #10
Source File: model.py    From python-libjuju with 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 #11
Source File: zmqrelay.py    From meshcat-python with 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 #12
Source File: node.py    From rewrite with 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 #13
Source File: test_coros.py    From wsstat with 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 #14
Source File: websockets.py    From python-binance-chain with 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 #15
Source File: BinanceWebsocket.py    From crypto-bot with 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 #16
Source File: websockets.py    From python-idex with 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 #17
Source File: bot.py    From pollmaster with 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 #18
Source File: bot.py    From pollmaster with 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 
Example #19
Source File: aoprotocol_ws.py    From tsuserver3 with GNU Affero General Public License v3.0 5 votes vote down vote up
def ws_try_writing_message(self, message):
            """
            Try writing the message if the client has not already closed
            the connection.
            """
            try:
                await self.ws.send(message)
            except ConnectionClosed:
                return 
Example #20
Source File: websockets_lib.py    From graphql-ws with MIT License 5 votes vote down vote up
def receive(self):
        try:
            msg = await self.ws.recv()
            return msg
        except ConnectionClosed:
            raise ConnectionClosedException() 
Example #21
Source File: connection.py    From python-libjuju with 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 #22
Source File: connection.py    From python-libjuju with 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 File: connection.py    From python-libjuju with 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 #24
Source File: webrtc.py    From brave with 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 #25
Source File: websockets_handler.py    From brave with 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 #26
Source File: test_protocol.py    From saltyrtc-server-python with 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 #27
Source File: test_protocol.py    From saltyrtc-server-python with 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 #28
Source File: protocol.py    From saltyrtc-server-python with 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 #29
Source File: protocol.py    From saltyrtc-server-python with 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 #30
Source File: protocol.py    From saltyrtc-server-python with 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