python - python websockets,如何设置连接超时
问题描述
假设 WebSocket 服务器暂时关闭,它丢弃传入的数据包(而不是拒绝它们)
目前,连接尝试和连接之间大约需要 95 秒TimeoutError
我似乎找不到减少该窗口的方法(所以我可以尝试另一个 WebSocket 服务器)
这是我正在运行的演示代码:(仅取自官方文档
#!/usr/bin/env python
import asyncio
import websockets
import os
import socket
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(name)s.%(funcName)s:%(lineno)d]: %(message)s', datefmt='%m-%d %H:%M:%S', )
host = os.environ.get('SERVER_URL','localhost:9090')
self_id = os.environ.get('SELF_ID',socket.gethostname())
connect_url =f'ws://{host}/{self_id}'
logging.info(f'Connect to: {connect_url}')
async def hello(uri):
logging.info(f'Connecting to {uri}')
async with websockets.connect(uri, timeout=1, close_timeout=1) as websocket:
logging.info(f"Conected to {uri}")
async for message in websocket:
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(
hello(connect_url))
解决方案
您可以像这样使用 asyncio 的 wait_for() :
import asyncio
from concurrent.futures import TimeoutError as ConnectionTimeoutError
# whatever url is your websocket server
url = 'ws://localhost:9090'
# timeout in seconds
timeout = 10
try:
# make connection attempt
connection = await asyncio.wait_for(websockets.connect(url), timeout)
except ConnectionTimeoutError as e:
# handle error
print('Error connecting.')
它将引发一个<class 'concurrent.futures._base.TimeoutError'>
异常,该异常可以被except ConnectionTimeoutError
块捕获。
在 python3.8 中,它提出了一个TimeoutError
可以被except asyncio.exceptions.TimeoutError
块捕获的。
推荐阅读
- flutter - 如何通过数据透视表获取标签的相关列表 - Flutter - Moor
- c# - 如何以正确的方式完成频道?如何使用多个渠道?
- machine-learning - ipython笔记本中的数据缓存问题
- sql - 加入以获取小于或等于的最后日期
- laravel - Laravel 关系不活跃的父级
- python - 如何在 BeautifulSoup4 中获取多个类名
- html - 更改标题 css 的大小
- python - 修复 ValueError:无法将字符串转换为浮点数:
- amazon-web-services - 将 AWS S3 服务与 json 文件集成为路径覆盖的 GET API 的 If-Modified-Since 标头
- query-optimization - AWS boto3 如何提高查询 DynamoDB 的性能