How to shut down a TCPServer serve_forever() loop?

John Pote johnpote at jptechnical.co.uk
Sat Nov 25 09:10:57 EST 2017


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?

Regards,

JOhn




More information about the Python-list mailing list