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

会有一股神秘感。 提交于 2019-12-10 08:46:00

问题


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.


回答1:


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()



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/5178536/in-python-how-to-get-a-udpserver-to-shutdown-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!