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

Search Discussions

  • Cmcp at Feb 28, 2011 at 12:34 pm
    In method StopServer() of class MyServer try calling self.server_close() after the self.shutdown() call. I believe this will actually close the server's socket and allow its reuse.
  • Massi at Feb 28, 2011 at 1:09 pm

    On 28 Feb, 13:34, cmcp wrote:
    In method StopServer() of class MyServer try calling ?self.server_close() after the self.shutdown() call. ?I believe this will actually close the server's socket and allow its reuse.
    It works! Thank you!!

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedFeb 28, '11 at 10:58a
activeFeb 28, '11 at 1:09p
posts3
users2
websitepython.org

2 users in discussion

Massi: 2 posts Cmcp: 1 post

People

Translate

site design / logo © 2022 Grokbase