2
votes

This are some the code that I used for my udp server. My problem is when I call the method terminate, It will only stop the listening loop after it receives another message from udp socket. I want to stop the thread immediately when I call terminate method. Or is there a better way of doing this? Thanks

    class StartThread:
        def __init__(self):
            self._running = True
            self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.s.bind(("0.0.0.0", 1234))        

        def terminate(self):
            self._running = False

        def run(self):    
            while  self._running:
                data, addr = self.s.recvfrom(1024)

c = StartThread()
t = Thread(target=c.run)
t.start()  
2
You can have a look at import select or import twisted(needs to be installed) for alternatives to threads.User

2 Answers

2
votes

in your terminate method, you can call s.shutdown() and s.close(). this should trigger the blocking call to terminate immediately.

2
votes

In addition to staticd answer, (which is fine), there are alternatives:

You could use a volatile boolean 'terminate' member that is checked after every recvfrom() return. Set the flag, then send an empty datagram on localhost to make the call return.

You could check every received datagram for a value that has no other meaning in your protocol, eg 'STOP'. Send such a datagram on localhost.

TBH, I would just shutdown() the socket, it's easier.