python websockets,如何设置连接超时

时间:2019-01-29 12:25:57

标签: python python-3.x websocket

让我们说WebSocket服务器是暂时关闭的,它会丢弃传入的数据包(而不是拒绝它们)

当前,从连接尝试到TimeoutError

大约需要95秒

我似乎找不到缩小窗口的方法(因此我可以尝试其他WebSocket服务器)

这是我正在运行的演示代码:(仅取自official docs

#!/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))

1 个答案:

答案 0 :(得分:0)

您可以像这样使用asyncio的wait_for():

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块捕获。