如何优雅地结束SocketServer

时间:2015-05-13 02:26:51

标签: python multithreading sockets

如果可能的话,我想留在std lib中。我的所有线程都运行了,套接字会正确地监听。我需要能够优雅地关闭套接字,但我似乎无法回复它们以便正常关闭。

问题是,当我到达server_close()时,它会炸毁我(请参阅下面的异常跟踪输出)。

感谢您的期待!

@Override
public void addNotify() {
    super.addNotify();
    requestFocusInWindow();
}

我得到的异常堆栈跟踪是:

import sys
import threading
import SocketServer


class EchoRequestHandler(SocketServer.BaseRequestHandler):

    def __init__(self, request, client_address, server):
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
        return

    def setup(self):
        return SocketServer.BaseRequestHandler.setup(self)

    def handle(self):
        # Echo the back to the client
        data = self.request.recv(1024)
        return

    def finish(self):
        return SocketServer.BaseRequestHandler.finish(self)


class EchoServer(SocketServer.TCPServer):

    def __init__(self, server_address, handler_class=EchoRequestHandler):
        SocketServer.TCPServer.__init__(self, server_address, handler_class)
        return

    def server_activate(self):
        SocketServer.TCPServer.server_activate(self)
        return

    def serve_forever(self):
        while True:
            self.handle_request()
        return

    def server_close(self):
        return SocketServer.TCPServer.server_close(self)



def bind_sockets(port_list):

    server_list = []
    for port in port_list:

        server = EchoServer(("", int(port)), EchoRequestHandler)
        server_thread = threading.Thread(target=server.serve_forever)
        server_thread.setDaemon(True)
        server_thread.start()
        server_list.append(server)
        print "listening on port", port

    return server_list


def main():

    port_list = [12345,54321]

    active_servers = bind_sockets(port_list)

    print "Hit Q to quit or R to reload."

    while 1:
        key_press = sys.stdin.read(1)

        if key_press == "q":
            sys.exit(2)
        elif key_press == "r":
            #We need to close gracefully so we can go on to do other stuff.
            print active_servers.__len__()
            for server in active_servers:
                server.server_close()
                print "closed"


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

你有两个问题:

  • 你需要调用shutdown()
  • 您不应该覆盖server_forever()
像这样:

# don't overrule server_forever, the default implementation
# handles the shutdown()
#def serve_forever(self):
#    while True:
#        self.handle_request()
#    return

def server_close(self):
    self.shutdown()
    return SocketServer.TCPServer.server_close(self)