How to shut down a TCPServer serve_forever() loop?

Ian Kelly ian.g.kelly at gmail.com
Mon Nov 27 17:44:30 EST 2017


On Sat, Nov 25, 2017 at 7:10 AM, John Pote <johnpote at jptechnical.co.uk> wrote:
> Hi all,
>
> My problem in summary is that my use of the shutdown() method only shuts
> down a server after the next TCP request is received.
>
> I have a TCP server created in the run() method of a thread.
>
>     class TCPlistener( Thread ):
>         def run( self ):
>            with socketserver.TCPServer(  ("localhost", 9999), ConnHandler )
> as server:
>                 self.server = server
>                 print( "TCP listener on: %s:%d" % ( self.host, self.port ) )
>                 self.server.serve_forever()
>
>                 print( "TCPlistener:run() ending" )
>
> ConnHandler is a simple echo class with only a handle() method
>
> The main bit of the program is
>
>     if __name__ == "__main__":
>         serverThrd = TCPlistener()
>         serverThrd.start()            #start TCP IP server listening
>         print("server started")
>
>         ch = getche()                    #wait for key press
>         print()
>         serverThrd.server.shutdown()
>
>         print( "main ending" )
>
> Everying works as expected, numerous connections can be made and the
> received text is echoed back.
>
> The issue is that if I press a key on the keyboard the key is immediately
> shown on the screen but then the shutdown() call blocks until another TCP
> connection is made, text is echoed back and only then does
> serve_forever()return followed by shutdown()returning as can be seen from
> the console session,
>
>>>python36 TCPIPserver.py
> server started
> TCP listener on: localhost:9999
> q #pressed 'q' key
> 127.0.0.1 wrote: #Sent some text from PuTTY
> b'SOME TEXT'
> TCPlistener:run() ending
> main ending
>
> How can I get shutdown()to shut down the server immediately without waiting
> for the next TCP connection?

Make a connection to the server after calling shutdown to wake up the
server's event loop? I'm guessing it only checks the shutdown flag
after responding to an event, so there's probably not much else you could do.



More information about the Python-list mailing list