I'm working on a Python-3 program that is trying to do two things: (1) Read data (Type 1) from an external websocket (non-blocking) and (2) Receive data (Type 2) on a regular UDP socket (non-blocking)
There are long periods of time where there is no data on neither the websocket nor the UDP socket. As such, I'm attempting to make both reads/receives for both data types non-blocking. I'm attempting to use Asyncio and Websockets to perform this for the websocket.
Unfortunately, the code below hangs whenever there is not data (Type 1) on the websocket. It blocks the rest of the code from executing. What am I doing wrong?
Thanks in advance for all the help.
import asyncio
import websockets
import socket
IP_STRATUX = "ws://192.168.86.201/traffic"
# Method to retrieve data (Type 1) from websocket
async def readWsStratux(inURL):
async with websockets.connect(inURL, close_timeout=0.1) as websocket:
try:
data = await websocket.recv()
return data
except websocket.error:
return None
if __name__ == "__main__":
# Socket to receive data (Type 2)
sockPCC = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockPCC.bind((PCC_IP, PCC_PORT))
sockPCC.setblocking(0)
while True:
print('-----MAIN LOOP-----')
data1 = asyncio.get_event_loop().run_until_complete(
readWsStratux(IP_STRATUX))
print(f'Data 1: {data1}')
data2, addr = sockPCC.recvfrom(1024)
print(f'Data 2: {data2}')