SocketServer:摆脱'[Errno 98]已经在使用的地址'

raf*_*afi 15 python socketserver python-2.7

我一直在查看文档SocketServer.我从文档中复制了TCP服务器代码,运行正常.但是,我注意到每当我在终端中按程序ctrl-c'ed,然后尝试再次运行它时,我会收到以下错误:

socket.error: [Errno 98] Address already in use
Run Code Online (Sandbox Code Playgroud)

我通过阅读本文本文来研究如何解决问题.我在代码中添加了以下行以尝试允许重用地址:

server.allow_reuse_address = True
Run Code Online (Sandbox Code Playgroud)

即使添加了上面的行,我仍然遇到同样的问题.我还添加了一个tryexcept我的server.serve_forever()函数,捕获KeyboardInterrupt异常并调用,server.shutdown()server.socket.close()希望释放该地址.

这是我的TCP服务器代码的完整范围(注意:我排除了MyTCPHandler类):

if __name__ == "__main__":
    HOST, PORT = '', 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.allow_reuse_address = True

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        server.socket.close()
Run Code Online (Sandbox Code Playgroud)

我仍然在运行上面的代码时出错,必须等待一分钟,直到地址最终被释放.当我不断调试和更改代码时,这很令人沮丧.

我在运行Raspbian"Wheezy"7.0的RaspberryPi上使用Python 2.7.3运行此代码.

tid*_*idy 22

...
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
...
Run Code Online (Sandbox Code Playgroud)

allow_reuse_address 应该在课堂上,而不是在实例上.