本文整理匯總了Python中websockets.ConnectionClosed方法的典型用法代碼示例。如果您正苦於以下問題:Python websockets.ConnectionClosed方法的具體用法?Python websockets.ConnectionClosed怎麽用?Python websockets.ConnectionClosed使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類websockets
的用法示例。
在下文中一共展示了websockets.ConnectionClosed方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: send
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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
示例2: test_explicit_permanent_key_unavailable
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例3: block_until
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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')
示例4: _recv_loop
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例5: _listen
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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))
示例6: listen
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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))
示例7: recv_handler
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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
示例8: __worker
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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)
示例9: _ws_ping_loop
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例10: _ws_loop
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例11: send_message
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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
示例12: _run
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例13: do_deploy
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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()
示例14: receive
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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
示例15: ping
# 需要導入模塊: import websockets [as 別名]
# 或者: from websockets import ConnectionClosed [as 別名]
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)