In python, how to make UDPServer disconnect?

I created a class for the server with the declaration:

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

And he began with:

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

My question is: how can I make the server shut down? I saw that it has a base class (base class) called BaseServer with a shutdown method. It can be called on someServer using someServer.shutdown() , but this is from outside the server itself.

+4
source share
3 answers

Using threads. Serving with one thread and passing through another after your timeout. Consider this working example. Change 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() 
+1
source

You can use twisted. Its an example of the best network library for python, here is an example of a UDP server, which here (taken from twisted documentation) is 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 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 by clicking self.transport.loseConnection() when you are ready or a specific event will occur.

+1
source

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

0
source

Source: https://habr.com/ru/post/1342092/


All Articles