M
Magnus Lycka
I have a socket server like below which I want to exit when
it's out of data. If I interrupt the client, I'll get a
broken pipe on the server side, and after a Ctrl-C, I can
restart the server again, but if I let it run out of data,
and exit via handle_error as can be seen below, I will get
a socket.error: (98, 'Address already in use') when I try
to restart the server. (Unless I wait a minute or so, or
use another port.) I feel like I'm waving a dead chicken
here. I can't seem to find any proper description on how to
handle this in the docs for SocketServer or socket, and my
futile experiments seem to lead nowhere... Neither Nutshell
nor the Essential Reference helped me solve this.
I'm using Python 2.2.3 on Linux. Why doesn't my socket
get released by the OS when I exit via my handle_error?
class MyRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
while True:
[snip]
try:
[snip]
except [snip]:
# Done!
# Uncommenting the next line makes no difference
# self.request.close()
sys.exit()
class ExitableSocketServer(SocketServer.TCPServer):
def handle_error(self, request, client_address):
exc_info = sys.exc_info()
if exc_info and isinstance(exc_info[1], SystemExit):
request.shutdown(2)
request.close()
del request
self.socket.shutdown(2)
self.socket.close()
del self.socket
sys.exit()
SocketServer.TCPServer.handle_error(self, request, client_address)
....
server = ExitableSocketServer(('', port), MyRequestHandler)
server.serve_forever()
it's out of data. If I interrupt the client, I'll get a
broken pipe on the server side, and after a Ctrl-C, I can
restart the server again, but if I let it run out of data,
and exit via handle_error as can be seen below, I will get
a socket.error: (98, 'Address already in use') when I try
to restart the server. (Unless I wait a minute or so, or
use another port.) I feel like I'm waving a dead chicken
here. I can't seem to find any proper description on how to
handle this in the docs for SocketServer or socket, and my
futile experiments seem to lead nowhere... Neither Nutshell
nor the Essential Reference helped me solve this.
I'm using Python 2.2.3 on Linux. Why doesn't my socket
get released by the OS when I exit via my handle_error?
class MyRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
while True:
[snip]
try:
[snip]
except [snip]:
# Done!
# Uncommenting the next line makes no difference
# self.request.close()
sys.exit()
class ExitableSocketServer(SocketServer.TCPServer):
def handle_error(self, request, client_address):
exc_info = sys.exc_info()
if exc_info and isinstance(exc_info[1], SystemExit):
request.shutdown(2)
request.close()
del request
self.socket.shutdown(2)
self.socket.close()
del self.socket
sys.exit()
SocketServer.TCPServer.handle_error(self, request, client_address)
....
server = ExitableSocketServer(('', port), MyRequestHandler)
server.serve_forever()