Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';t在SocketServer.TCPServer中重用套接字_Python_Sockets_Socketserver - Fatal编程技术网

Python Can';t在SocketServer.TCPServer中重用套接字

Python Can';t在SocketServer.TCPServer中重用套接字,python,sockets,socketserver,Python,Sockets,Socketserver,我在SocketServer.TCPServer上遇到问题。我正在线程中运行服务器。使用监视程序监视目录树。当“on_any_事件”运行时,我需要关闭服务器并再次启动它。很遗憾,我无法让SocketServer.TCPServer重用该地址。我已经检查了SocketServer.py文件,如果allow\u reuse\u address为True,则应该将socket.SO\u REUSEADDR设置为1。它仍然失败,错误:[Errno 98]地址已在使用中 不过。在重试之前睡上10秒钟也没用

我在SocketServer.TCPServer上遇到问题。我正在线程中运行服务器。使用监视程序监视目录树。当“on_any_事件”运行时,我需要关闭服务器并再次启动它。很遗憾,我无法让SocketServer.TCPServer重用该地址。我已经检查了SocketServer.py文件,如果
allow\u reuse\u address
为True,则应该将
socket.SO\u REUSEADDR
设置为1。它仍然失败,错误:[Errno 98]地址已在使用中 不过。在重试之前睡上10秒钟也没用。有什么帮助吗

class Server(SocketServer.TCPServer):
    allow_reuse_address = True

class ChangeHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)
        self.rebuild()

    def on_any_event(self, event):
        print event
        self.httpd.shutdown()
        self.t.join()
        self.rebuild()

    def rebuild(self):
        self.t, self.httpd = runserver()

def runserver():
    handler = SimpleHTTPServer.SimpleHTTPRequestHandler
    httpd = Server((HOST, PORT), handler, bind_and_activate=False)
    httpd.server_bind()
    httpd.server_activate()
    t = threading.Thread(target=httpd.serve_forever)
    t.daemon = True
    t.start()
    print "Live at http://{0}:{1}".format(HOST, PORT)
    return t, httpd

if __name__ == "__main__":
    handler = ChangeHandler()
    observer = Observer()
    observer.schedule(handler, path=ROOT, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

self.httpd.shutdown()
之后添加
self.httpd.server\u close()
成功了。

TCPServer实现了未记录的方法server\u close(),在事件处理程序中的self.t.join()之前或之后调用此函数,因为这实际上会关闭底层套接字。如前所述,您可能正在泄漏一个套接字

def on_any_event(self, event):
    print event
    self.httpd.shutdown()
    self.httpd.server_close() # actually close the socket
    self.t.join()
    self.rebuild()

在您关闭套接字之前,该地址实际上正在使用。

您在哪个平台上:Linux、Windows、OS X?其实这并不重要,但是…Linux。Ubuntu 11.04。Python 2.7.1“我需要关闭服务器并重新启动它”。为什么?没有文档的方法总是很好的。谢谢你的帮助:)