SocketServer problem: client hangs trying to reconnect after server restart

Discussion in 'Python' started by Massi, Feb 28, 2011.

  1. Massi

    Massi Guest

    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!
    Massi, Feb 28, 2011
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    575
  2. John_Woo
    Replies:
    0
    Views:
    1,334
    John_Woo
    Jun 8, 2006
  3. davy zhang
    Replies:
    0
    Views:
    454
    davy zhang
    Oct 25, 2008
  4. Replies:
    3
    Views:
    106
    beegee
    Jun 20, 2008
  5. Josef Moellers

    Restart Perl Application upon KDE Restart

    Josef Moellers, Jul 18, 2013, in forum: Perl Misc
    Replies:
    18
    Views:
    275
    Adam H. Kerman
    Jul 26, 2013
Loading...

Share This Page