How to process websocket data in a non-blocking manner?
The below example shows that when ws.recv()
is called and nothing is received, ws.recv()
blocks the rest of the code from running:
from websocket import create_connection
url = 'ws://example.com'
ws = create_connection(url)
ws.recv() # blocks
How to implement something along the lines of (without blocking):
from websocket import create_connection
url = 'ws://example.com'
ws = create_connection(url)
# non-blocking
if ws.not_empty():
ws.recv()
How to process websocket data in a non-blocking manner?
答案 0 :(得分:1)
If using Python >= 3.5 is an option, you might want to check out asyncio
which allows you to write single-threaded, yet concurrent code. This is typically useful for handling i/o bound code such as networking.
Be aware there is a bit of a learning curve if its your first time using asyncio
.
Once you've familiarized yourself with the basics, there is an excellent websockets
module which leverages asyncio
: