python websocket recv timeout code example

Example: 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  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.

Tags:

Misc Example