本文整理汇总了Python中websockets.exceptions.ConnectionClosed方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ConnectionClosed方法的具体用法?Python exceptions.ConnectionClosed怎么用?Python exceptions.ConnectionClosed使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类websockets.exceptions
的用法示例。
在下文中一共展示了exceptions.ConnectionClosed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _receive
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _receive(self) -> str:
"""Wait the next message from the websocket connection and log the answer
"""
# We should always have an active websocket connection here
assert self.websocket is not None
# Wait for the next websocket frame. Can raise ConnectionClosed
data: Data = await self.websocket.recv()
# websocket.recv() can return either str or bytes
# In our case, we should receive only str here
if not isinstance(data, str):
raise TransportProtocolError("Binary data received in the websocket")
answer: str = data
log.info("<<< %s", answer)
return answer
示例2: _attempt_connection
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _attempt_connection(self, fn_name, arg=None):
fn = self._interface.node.__getattribute__(fn_name)
self._interface.node.thread_shutdown = True
self._interface.node.heartbeat_thread.join()
self._interface.node.thread_shutdown = False
try:
#debug(); pdb.set_trace()
if arg:
return fn(arg)
else:
return fn()
except StaleBlockchain:
self._scene.add_effect( MessageDialog(self._screen, "Stale blockchain on selected Node"))
return
#except (AttributeError, InvalidStatusCode, ConnectionClosed, TimeoutError, OSError) as e: #Timeout
# self._scene.add_effect( MessageDialog(self._screen, "Could not connect to node ({})".format(str(e.__class__))))
# return
self._interface.node.start_heartbeat_thread()
示例3: _feed_buffer
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _feed_buffer(self, n=1):
"""
Feed the data buffer by reading a Websocket message.
:param n: if given, feed buffer until it contains at least n bytes
"""
buffer = bytearray(self._stream.read())
while len(buffer) < n:
try:
message = yield from self._protocol.recv()
except ConnectionClosed:
message = None
if message is None:
break
if not isinstance(message, bytes):
raise TypeError("message must be bytes")
buffer.extend(message)
self._stream = io.BytesIO(buffer)
示例4: _inner_messages
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
if ((msg != "{\"event\":\"heartbeat\"}" and
"\"event\":\"systemStatus\"" not in msg and
"\"event\":\"subscriptionStatus\"" not in msg)):
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例5: _inner_messages
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
# get required data to create a websocket request
示例6: _inner_messages
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _inner_messages(self,
ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例7: _get_response
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _get_response(self, ws: websockets.WebSocketClientProtocol):
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
self._last_recv_time = time.time()
yield msg
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例8: _inner_messages
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _inner_messages(self, ws: websockets.WebSocketClientProtocol) -> AsyncIterable[str]:
# Terminate the recv() loop as soon as the next message timed out, so the outer loop can reconnect.
try:
while True:
try:
msg: str = await asyncio.wait_for(ws.recv(), timeout=self.MESSAGE_TIMEOUT)
yield msg
except asyncio.TimeoutError:
try:
pong_waiter = await ws.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await ws.close()
示例9: _messages
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _messages(self) -> AsyncIterable[Any]:
try:
while True:
try:
raw_msg_str: str = await asyncio.wait_for(self._client.recv(), timeout=self.MESSAGE_TIMEOUT)
raw_msg = ujson.loads(raw_msg_str)
yield raw_to_response(raw_msg)
except asyncio.TimeoutError:
try:
pong_waiter = await self._client.ping()
await asyncio.wait_for(pong_waiter, timeout=self.PING_TIMEOUT)
except asyncio.TimeoutError:
raise
except asyncio.TimeoutError:
self.logger().warning("WebSocket ping timed out. Going to reconnect...")
return
except ConnectionClosed:
return
finally:
await self.disconnect()
# emit messages
示例10: _send
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _send(self, message: str) -> None:
"""Send the provided message to the websocket connection and log the message
"""
if not self.websocket:
raise TransportClosed(
"Transport is not connected"
) from self.close_exception
try:
await self.websocket.send(message)
log.info(">>> %s", message)
except ConnectionClosed as e:
await self._fail(e, clean_close=False)
raise e
示例11: get_server_handler
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def get_server_handler(request):
"""Get the server handler.
Either get it from test or use the default server handler
if the test provides only an array of answers.
"""
if isinstance(request.param, types.FunctionType):
server_handler = request.param
else:
answers = request.param
async def default_server_handler(ws, path):
try:
await WebSocketServer.send_connection_ack(ws)
query_id = 1
for answer in answers:
result = await ws.recv()
print(f"Server received: {result}")
if isinstance(answer, str) and "{query_id}" in answer:
answer_format_params = {"query_id": query_id}
formatted_answer = answer.format(**answer_format_params)
else:
formatted_answer = answer
await ws.send(formatted_answer)
await WebSocketServer.send_complete(ws, query_id)
query_id += 1
await WebSocketServer.wait_connection_terminate(ws)
await ws.wait_closed()
except ConnectionClosed:
pass
server_handler = default_server_handler
return server_handler
示例12: _run_socket
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def _run_socket(self):
retries = 0
sId = len(self.sockets)
s = Socket(sId)
self.sockets[sId] = s
loop = asyncio.get_event_loop()
while retries < self.max_retries and self.attempt_retry:
try:
async with websockets.connect(self.host) as websocket:
self.sockets[sId].set_websocket(websocket)
self.sockets[sId].set_connected()
self.logger.info("Websocket connected to {}".format(self.host))
retries = 0
while True:
# optimization - wait 0 seconds to force the async queue
# to be cleared before continuing
await asyncio.sleep(0)
message = await websocket.recv()
await self.on_message(sId, message)
except (ConnectionClosed, socket.error) as e:
self.sockets[sId].set_disconnected()
if self.sockets[sId].isAuthenticated:
self.sockets[sId].set_unauthenticated()
self._emit('disconnected')
if (not self.attempt_retry):
return
self.logger.error(str(e))
retries += 1
# wait 5 seconds befor retrying
self.logger.info("Waiting 5 seconds before retrying...")
await asyncio.sleep(5)
self.logger.info("Reconnect attempt {}/{}".format(retries, self.max_retries))
self.logger.info("Unable to connect to websocket.")
self._emit('stopped')
示例13: recv
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def recv(self):
if not self.responses:
await asyncio.sleep(1) # delay to give test time to finish
raise ConnectionClosed(0, 'ran out of responses')
return json.dumps(self.responses.popleft())
示例14: connect_schwifty
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def connect_schwifty(self):
self.schwifty = await SchwiftyWebsocket.create(
self.shard,
self
)
while not self.is_closed:
try:
await self.schwifty.poll_event()
except (ConnectionClosed, asyncio.TimeoutError) as e:
await asyncio.sleep(1)
self.schwifty = await SchwiftyWebsocket.create(
self.shard,
self
)
示例15: chrome_tab
# 需要导入模块: from websockets import exceptions [as 别名]
# 或者: from websockets.exceptions import ConnectionClosed [as 别名]
def chrome_tab():
"""Ensure Chrome is running
"""
browser = ChromeMock(host=TEST_HOST, port=TEST_PORT)
await browser.connect()
chrome_tab = browser.tabs[0]
yield chrome_tab
print("gracefully disconnecting chrome tab...")
try:
await chrome_tab.disconnect()
except ConnectionClosed:
pass