Home > Mobile >  python check socket receive within other loop -- non-blocking?
python check socket receive within other loop -- non-blocking?

Time:10-09

I know the code to wait for socket in a loop like this.

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
data, addr = s.recvfrom(1024)
data = data.decode('utf-8')
print("Message from: "   str(addr))
print("From connected user: "   data)
com = data
data = data.upper()
data = "Message Received: "   data

however, I want to use this function in another main loop that refreshes every second. When this get called it freezes until meeting any msg.

Is there any way that I can "check msg" on off, and integrate this in the main loop refreshes every second?

Many thanks.

CodePudding user response:

You can use select.select to poll for readiness to receive a message:

import socket
import select

s = socket.socket(type=socket.SOCK_DGRAM)
s.bind(('', 5000))
while True:
    r, _, _ = select.select([s], [], [], 1.0)
    if r:  # r will contain s if a message is ready
        data, addr = s.recvfrom(1024)
        data = data.decode('utf-8')
        print(f'\n{addr}: {data}')
    else:
        print('.', end='', flush=True) # show activity
  • Related