我遇到了SocketServer.TCPServer的问题.我正在一个线程中运行一个服务器.用Watchdog监视目录树.当“on_any_event”运行时,我需要取下服务器并重新启动它.不幸的是我无法让SocketServer.TCPServer重用该地址.我检查了SocketServer.py文件,如果allow_reuse_address为True,则应将socket.SO_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()
最佳答案 TCPServer实现了未记录的方法server_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()
在关闭套接字之前,地址实际上正在使用中.