代码之家  ›  专栏  ›  技术社区  ›  SimSimY

python websockets,如何设置连接超时

  •  1
  • SimSimY  · 技术社区  · 6 年前

    目前,连接尝试和 TimeoutError

    我似乎找不到一种方法来减少这个窗口(所以我可以尝试另一个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))
    
    0 回复  |  直到 6 年前
        1
  •  2
  •   Joules    4 年前

    可以使用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 阻止。