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!
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!