How to use the websockets.exceptions.ConnectionClosedOK 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 machinezone / cobra / cobras / client / connection.py View on Github external
msgId = data.get('id')
                if msgId is None:
                    raise ActionException('server bug: incoming message has no id')

                action = data['action']
                action = '/'.join(action.split('/')[:2])
                actionId = action + '::' + str(msgId)

                if action == 'rtm/subscription':
                    actionId = action + '::' + data['body']['subscription_id']

                q = self.getQueue(actionId)

                await q.put(data)

        except websockets.exceptions.ConnectionClosedOK as e:
            self.stop.set_result(e)

        except Exception as e:
            logging.error(f'unexpected exception: {e}')
            self.stop.set_result(e)

        finally:
            if len(self.queues) != 0:
                logging.warning(f'connection has pending queues: {self.queues}')
github machinezone / cobra / cobras / client / client.py View on Github external
await connection.connect()
            return await clientCallback(connection)

        except TimeoutError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except ConnectionRefusedError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except ConnectionResetError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.ConnectionClosedOK as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.ConnectionClosedError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.InvalidMessage as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except OSError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except EOFError as e:
github augerai / a2ml / a2ml / server / server.py View on Github external
try:
                notificator = AsyncReceiver(id, last_msg_id)
                try:
                    while True:
                        try:
                            # Periodically iterrupt waiting of message from subscription
                            # to check is websocket is still alive or not
                            reply = await asyncio.wait_for(notificator.get_message(), timeout=5.0)
                            if reply:
                                log("Broadcast: ", repr(reply))
                                await websocket.send_text(reply)
                            else:
                                await websocket.send_json({"type": "ping"}, mode="text")
                        except asyncio.TimeoutError:
                            await websocket.send_json({"type": "ping"}, mode="text")
                except (websockets.exceptions.ConnectionClosedOK, websockets.exceptions.ConnectionClosedError) as e:
                    log(f"WebSocket {id} disconnected: {str(e)}")
            finally:
                await notificator.close()
    finally:
        log('WebSocket stopped')
        await websocket.close()
github crotwell / seisplotjs / docs / examples / viewobspy / serveobspy.py View on Github external
async def consumer_handler(self, websocket, path):
        try:
            while True:
                message = await websocket.recv()
                logger.debug("got message from ws "+message)
        except websockets.exceptions.ConnectionClosedOK:
            pass
        except Exception as e:
            logger.error("consumer_handler exception ", exc_info=e)
        except:
            e = sys.exc_info()[0]
            logger.error('consumer_handler something bad happened  ', exc_info=e)
    async def producer_handler(self, websocket, path):
github mitre / caldera / app / service / event_svc.py View on Github external
async def handle_exceptions(self, awaitable):
        try:
            return await awaitable
        except websockets.exceptions.ConnectionClosedOK:
            pass  # No handler was registered for this event
        except Exception as e:
            self.log.error("WebSocket error: {}".format(e), exc_info=True)
github machinezone / cobra / cobras / client / client.py View on Github external
await connection.connect()
            return await clientCallback(connection)

        except TimeoutError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except ConnectionRefusedError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except ConnectionResetError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.ConnectionClosedOK as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.ConnectionClosedError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except websockets.exceptions.InvalidMessage as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except OSError as e:
            logging.error(e)
            await asyncio.sleep(waitTime)
            pass
        except EOFError as e:
github sergio-ivanuzzo / idewave-core / Server / WebsocketServer / WebsocketServer.py View on Github external
async def accept_connection(self, websocket: WebSocketCommonProtocol):
        while True:
            try:
                request = await asyncio.wait_for(websocket.recv(), timeout=0.01)
            except TimeoutError:
                pass
            except ConnectionClosedOK:
                return
            else:
                parsed_request = json.loads(request)
                if 'type' in parsed_request and parsed_request['type'] == RequestType.SUBSCRIBE.value:
                    Logger.success('[Websocket Server]: new connection was added, {}'.format(websocket.local_address))
                    self.connections.append(websocket)
            finally:
                await asyncio.sleep(1)
github Truth0906 / PTTLibrary / PTTLibrary / ConnectCore.py View on Github external
Msg = ''
            ReceiveDataBuffer = bytes()

            StartTime = time.time()
            MidTime = time.time()
            while MidTime - StartTime < CurrentScreenTimeout:
                try:
                    asyncio.get_event_loop().run_until_complete(
                        WebsocketReceiver(self._Core, CurrentScreenTimeout)
                    )
                    ReceiveDataTemp = _WSRecvData

                except websockets.exceptions.ConnectionClosed:
                    raise Exceptions.ConnectionClosed()
                except websockets.exceptions.ConnectionClosedOK:
                    raise Exceptions.ConnectionClosed()
                except asyncio.TimeoutError:
                    return -1

                ReceiveDataBuffer += ReceiveDataTemp
                ReceiveDataTemp = ReceiveDataBuffer.decode(
                    'big5-uao', errors='replace'
                )
                Screen = self._cleanScreen(ReceiveDataTemp)

                FindTarget = False
                for Target in TargetList:

                    Condition = Target.isMatch(Screen)
                    if Condition:
                        if len(Screen) > 0:
github machinezone / cobra / cobras / server / app.py View on Github external
app['stats'].incrConnections(appkey)
    connectionCount = len(app['connections'])
    state.log(f'(open) connections {connectionCount}')

    try:
        async for message in websocket:
            msgCount += 1
            await processCobraMessage(state, websocket, app, message)
            if not state.ok:
                raise Exception(state.error)

    except websockets.exceptions.ProtocolError as e:
        print(e)
        state.log('Protocol error')
    except websockets.exceptions.ConnectionClosedOK:
        state.log('Connection closed properly')
    except websockets.exceptions.ConnectionClosedError:
        state.log('Connection closed with an error')
    except Exception as e:
        print(e)
        print('Generic Exception caught in {}'.format(traceback.format_exc()))
    finally:
        del app['connections'][key]

        subCount = len(state.subscriptions)

        if subCount > 0:
            state.log('cancelling #{} subscriptions'.format(subCount))
        for val in state.subscriptions.values():
            task, role = val
            app['stats'].decrSubscriptionsBy(role, 1)