pythonmultithreadingsocketserver

Stop UDP SocketServer


I'm creating an UDP SocketServer, and I would like to shutdown if I'm receiving a close message from the client side than I would like to close the UDP connection.

As I received the message the Begin will be displayed, but the Finished is not displayed. How can I exit from this thread?

class MyUDPHandler( SocketServer.BaseRequestHandler ):       
    def handle( self ):
        data = self.request[0].strip()        
        dic = self.string_XML_to_dic( data )
        if( dic['Cmd'] == str(UDPConst().SHUT_DOWN )): 
            print('Begin')           
            self.server.shutdown()
            print("Finished")

if __name__ == "__main__": 
    HOST, PORT = "", prop['udpport']
    server = SocketServer.UDPServer( ( HOST, PORT ), MyUDPHandler )    
    server.serve_forever()

Solution

  • As you are not running the server in it's own thread (you need to inherit ThreadingMixIn for that), you can not use shutdown as it will cause a deadlock. From the function document comment in the source:

    Blocks until the loop has finished. This must be called while serve_forever() is running in another thread, or it will deadlock.