python websocket recv timeout

Solutions on MaxInterview for python websocket recv timeout by the best coders in the world

showing results for - "python websocket recv timeout"
Emy
11 Jun 2018
1You can use asyncio's wait_for() like this:
2
3import asyncio
4from concurrent.futures import TimeoutError as ConnectionTimeoutError
5# whatever url is your websocket server
6url = 'ws://localhost:9090'
7# timeout in seconds
8timeout = 10  
9try:
10    # make connection attempt
11    connection = await asyncio.wait_for(websockets.connect(url), timeout)
12except ConnectionTimeoutError as e:
13    # handle error
14    print('Error connecting.')
15It will raise a <class 'concurrent.futures._base.TimeoutError'> exception which can be caught with the except ConnectionTimeoutError block.
16
17In python3.8 it raises a TimeoutError which can be caught with the except asyncio.exceptions.TimeoutError block.