I created a simple test application (Python 2.6.1) that runs ThreadingTCPServer, based on an example here . If the client sends a "bye" command, I want to close the server and exit the application. The output part is working fine, but when I try to restart the application, I get:
socket.error: [Errno 48] Address already in use
I tried the solution given here to configure the socket options, but that didn't seem to help. I tried various ways to close the server, but always get the same error.
Any idea what I'm doing wrong?
import SocketServer
import socket
import sys
import threading
import time
class RequestHandler(SocketServer.BaseRequestHandler):
def setup(self):
print("Connection received from %s" % str(self.client_address))
self.request.send("Welcome!\n")
def handle(self):
while 1:
data = self.request.recv(1024)
if (data.strip() == 'bye'):
print("Leaving server.")
self.finish()
self.server.shutdown()
break
def finish(self):
self.request.send("Goodbye! Please come back soon.")
if __name__ == "__main__":
server = SocketServer.ThreadingTCPServer(("localhost", 9999), RequestHandler)
server.serve_forever()
print("Exiting program.")
source
share