closing a "forever" Server Socket

alessandro dilbert01 at gmail.com
Thu Jan 18 13:29:41 CET 2007


Hi all,

This is my framework for create TCP server listening forever on a port
and supporting threads:


import SocketServer

port = 2222
ip = "192.168.0.4"
server_address = (ip, port)

class ThreadingTCPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer): pass

class Handler(SocketServer.BaseRequestHandler):
    def handle(self):
	# my handler

print "Listening for events at " + ip + ":" + str(port)
monitor_server = ThreadingTCPServer(server_address, Handler)

try:
    monitor_server.serve_forever()
except KeyboardInterrupt:
    monitor_server.socket.close()
    print "Bye."


This server will not run as a daemon and for quitting you have to send
the SIGINT signal with Ctrl-C. It will rise the KeyboardInterrupt
exception, during its handling I simply close the socket and print a
message.

I want to ask if someone knows a better way for closing a "forever
server" or if there is a lack in my design.

Thank you!

Alessandro




More information about the Python-list mailing list