[英]Can't reuse socket in SocketServer.TCPServer
I've got a problem with SocketServer.TCPServer. 我遇到了SocketServer.TCPServer的问题。 I'm running a server in a thread.
我正在一个线程中运行一个服务器。 Watching a directory tree with Watchdog.
用Watchdog监视目录树。 When "on_any_event" runs I need to take down the server and start it again.
当“on_any_event”运行时,我需要取下服务器并重新启动它。 Unfortunately I can't get SocketServer.TCPServer to reuse the address.
不幸的是我无法让SocketServer.TCPServer重用该地址。 I've checked the SocketServer.py file and if
allow_reuse_address
is True it is supposed to set socket.SO_REUSEADDR
to 1. It still fails with error: [Errno 98] Address already in use
though. 我检查了SocketServer.py文件,如果
allow_reuse_address
为True, socket.SO_REUSEADDR
将socket.SO_REUSEADDR
设置为1.它仍然会失败并显示error: [Errno 98] Address already in use
。 Sleeping for 10 secs before retrying doesn't help either. 在重试前睡觉10秒也无济于事。 Any help?
有帮助吗?
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 implements the undocumented method server_close(), call this before or after self.t.join() in your event handler, since that is what will actually close the underlying socket. TCPServer实现了未记录的方法server_close(),在事件处理程序中的self.t.join()之前或之后调用它,因为这将实际关闭底层套接字。 As written it looks like you may be potentially leaking a socket.
如上所述,看起来您可能正在泄漏套接字。
def on_any_event(self, event):
print event
self.httpd.shutdown()
self.httpd.server_close() # actually close the socket
self.t.join()
self.rebuild()
Until you close the socket the address actually is in use. 在关闭套接字之前,地址实际上正在使用中。
在self.httpd.server_close()
之后添加self.httpd.shutdown()
就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.