HTTPServer.shutdown返回但套接字仍处于打开状态

时间:2014-04-29 11:28:48

标签: python sockets httpserver

我使用以下代码在端口8000上运行本地HTTP服务器:

# Omitted imports and irrelevant things for brevity.

class ThreadedHTTPServer(SocketServer.ThreadingMixIn, HTTPServer):
    pass

class MyClass(object):

    server = None

    def start_server(self):
        handler = MyPageHandler
        self.server = ThreadedHTTPServer(('', 8000), handler)

        server_thread = threading.Thread(target=self.server.serve_forever)
        server_thread.daemon = False
        server_thread.start()

    def stop_server(self):
        self.server.shutdown()

然而,偶尔当stop_server返回时,监听套接字仍将打开。我已经通过将os.system("netstat -ln | grep 8000")放在stop_server的末尾来验证这一点,并且它经常显示套接字仍在监听。

套接字关闭后,是否只能从stop_server返回?

1 个答案:

答案 0 :(得分:3)

看起来这是通过添加server.server_close()作为@ρss建议来解决的:

def stop_server(self):
    self.server.shutdown()
    self.server.server_close()