Answers for "python websocket recv timeout"

0

python websocket recv timeout

You can use asyncio's wait_for() like this:

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.')
It will raise a <class 'concurrent.futures._base.TimeoutError'> exception which can be caught with the except ConnectionTimeoutError block.

In python3.8 it raises a TimeoutError which can be caught with the except asyncio.exceptions.TimeoutError block.
Posted by: Guest on March-20-2021

Python Answers by Framework

Browse Popular Code Answers by Language