简体   繁体   中英

In python, how to get a UDPServer to shutdown itself?

I've created a class for a server with the declaration:

class myServer(socketserver.BaseRequestHandler):  
    def handle(self):  
        pass

And started it with:

someServer = socketserver.UDPServer((HOST, PORT), myServer)  
someServer.serve_forever()

My question is: how can I get the server to shutdown itself? I've seen it has a base class (of a base class) called BaseServer with a shutdown method. It can be called on someServer with someServer.shutdown() but this is from the outside of the server itself.

You could use twisted. Its about the best networking lib for python, here is an example of a UDP server here is (taken from the twisted documentation) the simplest UDP server ever written;

#!/usr/bin/env python

# Copyright (c) 2001-2009 Twisted Matrix Laboratories.
# See LICENSE for details.

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor

# Here's a UDP version of the simplest possible protocol
class EchoUDP(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        self.transport.write(datagram, address)

def main():
    reactor.listenUDP(8000, EchoUDP())
    reactor.run()

if __name__ == '__main__':
    main()

You can then close this down by calling self.transport.loseConnection() When you are ready or a specific event happens.

By using threads. Serving by one thread and going via another after your timeout. Consider this working example. Modify it for your UDPServer

import threading
import time
import SimpleHTTPServer
import SocketServer

PORT = 8000
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)

def worker():

    # minimal web server.  serves files relative to the
    print "serving at port", PORT
    httpd.serve_forever()

def my_service():
    time.sleep(3)
    print "I am going down"
    httpd.shutdown()

h = threading.Thread(name='httpd', target=worker)
t = threading.Thread(name='timer', target=my_service)

h.start()
t.start()

The server instance is available as self.server in the handler class. So you can call self.server.shutdown() in the handle method.

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