SocketServer problem: client hangs trying to reconnect after server restart

M

Massi

Hi everyone!

in my script (Python 2.6 on windows 7) I have to set up a SocketServer
server and use it to handle external connections. During the execution
It can happen that this server should be closed and restarted (for
example with different port or host). The following piece of code
simulates the situation I have to deal with:

import SocketServer, socket, threading
from time import sleep
BUF_LENGTH = 1024

class MyHandler(SocketServer.BaseRequestHandler) :
def handle(self):
while 1:
data = self.request.recv(1024)
self.request.send(data)
if data.strip() == 'bye':
return

class MyServer(SocketServer.ThreadingTCPServer) :
def __init__(self, host, port, handler) :
self.allow_reuse_address = True
self.__handler = handler
self.__serving = True
SocketServer.ThreadingTCPServer.__init__ (self, (host, port),
handler)

def StartServer(self) :
self.serve_forever()

def StopServer(self) :
self.shutdown()

def Init() :
server = MyServer("localhost", 5000, MyHandler)
threading.Thread(target=server.StartServer).start()
sleep(0.5)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 5000))
sock.send("hi")
sock.recv(BUF_LENGTH)
sock.send("bye")
return server

def CleanUp(server) :
server.StopServer()

for i in range(3) :
print "---------- Connection: "+str(i)+" ----------"
server = Init()
CleanUp(server)

print "Finished"

If you ran the code you'll see that the client hangs after the first
connection. Can anyone point me out where I'm doing wrong? Thanks in
advance!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,954
Messages
2,570,116
Members
46,704
Latest member
BernadineF

Latest Threads

Top