我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用websocket.WebSocketException()。
def testRecvWithFireEventOfFragmentation(self): sock = ws.WebSocket(fire_cont_frame=True) s = sock.sock = SockMock() # OPCODE=TEXT, FIN=0, MSG="Brevity is " s.add_packet(six.b("\x01\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C")) # OPCODE=CONT, FIN=0, MSG="Brevity is " s.add_packet(six.b("\x00\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C")) # OPCODE=CONT, FIN=1, MSG="the soul of wit" s.add_packet(six.b("\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17")) _, data = sock.recv_data() self.assertEqual(data, six.b("Brevity is ")) _, data = sock.recv_data() self.assertEqual(data, six.b("Brevity is ")) _, data = sock.recv_data() self.assertEqual(data, six.b("the soul of wit")) # OPCODE=CONT, FIN=0, MSG="Brevity is " s.add_packet(six.b("\x80\x8babcd#\x10\x06\x12\x08\x16\x1aD\x08\x11C")) with self.assertRaises(ws.WebSocketException): sock.recv_data() with self.assertRaises(ws.WebSocketConnectionClosedException): sock.recv()
def _connect(self): logger.debug('ARI client listening...') try: with self._running(): self.client.run(apps=[APPLICATION_NAME]) except socket.error as e: if e.errno == errno.EPIPE: # bug in ari-py when calling client.close(): ignore it and stop logger.error('Error while listening for ARI events: %s', e) return else: self._connection_error(e) except (WebSocketException, HTTPError) as e: self._connection_error(e) except ValueError: logger.warning('Received non-JSON message from ARI... disconnecting') self.client.close()
def _recv_loop(self): while not self._stopped.is_set(): try: self._ws.settimeout(1) message_json = self._ws.recv() message = json.loads(message_json) except websocket.WebSocketTimeoutException: continue except (websocket.WebSocketException, OSError): if not self._stopped.is_set(): logger.error("websocket exception", exc_info=True) self._stopped.set() return if self.debug: # pragma: no cover print('< RECV %s' % message_json) if "method" in message: self.event_queue.put(message) elif "id" in message: if message["id"] in self.method_results: self.method_results[message['id']].put(message) else: # pragma: no cover warnings.warn("unknown message: %s" % message)
def _connect(self, port): """Connect to the websocket, retrying as needed. Returns the socket.""" was_running = False for i in range(120): is_running = self.running was_running = was_running or is_running if (i >= 30 or was_running) and not is_running: logging.warning( "SC2 isn't running, so bailing early on the websocket connection.") break logging.info("Connection attempt %s (running: %s)", i, is_running) time.sleep(1) try: return websocket.create_connection("ws://127.0.0.1:%s/sc2api" % port, timeout=2 * 60) # 2 minutes except socket.error: pass # SC2 hasn't started listening yet. except websocket.WebSocketException as err: if "Handshake Status 404" in str(err): pass # SC2 is listening, but hasn't set up the /sc2api endpoint yet. else: raise sys.exit("Failed to create the socket.")
def connect(self, room): """ connect(room) -> Bool Connect to the given room. Cannot send messages without first connecting. """ self.room = room url = "wss://%s/room/%s/ws" % (self.site, self.room) try: self.socket = websocket.create_connection(url, enable_multithread=True, timeout=40) except (websocket.WebSocketException, IOError): self.socket = None return False return True
def send_json(self, data): """ send_json(data) -> Bool Send json data into the stream. Returns false on message fail. """ now = time.time() if self.limit != 0 and now - self.last_packet < self.limit: time.sleep(self.limit - (now - self.last_packet)) try: self.socket.send(json.dumps(data)) except (AttributeError, websocket.WebSocketException): with self.lock: self.socket = None return False self.last_packet = time.time() return True
def receive_data(self): """ reveive_data() -> Bool Reveive a packet and send it to handle_packet() for proccessing. Returns false on message fail. """ if self.socket is None: return False try: raw = self.socket.recv() self.handle_packet(json.loads(raw)) except websocket.WebSocketException: with self.lock: self.socket = None return True
def testReadHeader(self): status, header = read_headers(HeaderSockMock("data/header01.txt")) self.assertEqual(status, 101) self.assertEqual(header["connection"], "upgrade") HeaderSockMock("data/header02.txt") self.assertRaises(ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt"))
def testRecvContFragmentation(self): sock = ws.WebSocket() s = sock.sock = SockMock() # OPCODE=CONT, FIN=1, MSG="the soul of wit" s.add_packet(six.b("\x80\x8fabcd\x15\n\x06D\x12\r\x16\x08A\r\x05D\x16\x0b\x17")) self.assertRaises(ws.WebSocketException, sock.recv)
def run_forever(self): """ This method is used to run the websocket app continuously. It will execute callbacks as defined and try to stay connected with the provided APIs """ cnt = 0 while True: cnt += 1 self.url = next(self.urls) log.debug("Trying to connect to node %s" % self.url) try: # websocket.enableTrace(True) self.ws = websocket.WebSocketApp( self.url, on_message=self.on_message, # on_data=self.on_message, on_error=self.on_error, on_close=self.on_close, on_open=self.on_open ) self.ws.run_forever() except websocket.WebSocketException as exc: if (self.num_retries >= 0 and cnt > self.num_retries): raise NumRetriesReached() sleeptime = (cnt - 1) * 2 if cnt < 10 else 10 if sleeptime: log.warning( "Lost connection to node during wsconnect(): %s (%d/%d) " % (self.url, cnt, self.num_retries) + "Retrying in %d seconds" % sleeptime ) time.sleep(sleeptime) except KeyboardInterrupt: self.ws.keep_running = False raise except Exception as e: log.critical("{}\n\n{}".format(str(e), traceback.format_exc()))
def testReadHeader(self): status, header = read_headers(HeaderSockMock("data/header01.txt")) self.assertEqual(status, 101) self.assertEqual(header["connection"], "Upgrade") HeaderSockMock("data/header02.txt") self.assertRaises(ws.WebSocketException, read_headers, HeaderSockMock("data/header02.txt"))
def connect(self): try: self.ws.connect(self.uri) except websocket.WebSocketException: raise MachineUnauthorizedError()
def receive_messages(self, controlq): self._trigger_worker = Thread(target=self.trigger_worker) self._trigger_worker.start() while True: try: try: if controlq.get_nowait() is StopIteration: raise except Empty: pass message = self.receive() if message is None: continue # print(json.dumps(message, indent=4)) if isinstance(message, Exception): self.dispatch_reply(message.id, message, []) elif 'id' in message: self.dispatch_reply(message['id'], message, []) else: self.dispatch_event(message) except (KeyboardInterrupt, StopIteration, websocket.WebSocketException) as e: logging.debug('Fatal receive message: {}'.format(e)) break self.dispatch_event(StopIteration) logging.info('Stopping receive thread')