简体   繁体   中英

Better way of reading UDP data in Python

Is there a better way of listening on a port and reading in UDP data?

I do a

self.udps.bind((self.address,self.port)
ata, addr = self.udps.recvfrom(1024)

It seems to get locked in this state until it gets that data, in a bare script or in a thread.

This works well, but if you want to say get it to stop listening, it won't until it receives data and moves on to realize it needs to stop listening. I've had to send UDP data to the port each time to get it to gracefully shut down. Is there a way to get it to stop listening immediately with a specific condition?

recfrom waits until data arrives on the specified port.

If you don't want it to listen forever, set a timeout:

self.udps.bind((self.address,self.port)
self.udps.settimeout(60.0)  # set 1min timeout
while some_condition:
    try:
        ata, addr = self.udps.recvfrom(1024)
    except socket.timeout:
        pass  # try again while some_condition
    else:
         # work with the received data ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM