python - SocketServer: 摆脱 '[Errno 98] Address already in use'

标签 python python-2.7 socketserver

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

socket.error: [Errno 98] Address already in use

我通过阅读 this 研究了如何解决这个问题。和 this .我在我的代码中添加了以下行以尝试允许重复使用该地址:

server.allow_reuse_address = True

即使添加了上述行,我仍然遇到同样的问题。我还在我的 server.serve_forever() 函数周围添加了一个 tryexcept,捕获 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()

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

我在运行 Raspbian“Wheezy”7.0 的 RaspberryPi 上使用 Python 2.7.3 运行这段代码。

最佳答案

...
SocketServer.TCPServer.allow_reuse_address = True
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
...

allow_reuse_address 应该在类上,而不是在实例上。

关于python - SocketServer: 摆脱 '[Errno 98] Address already in use',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16433522/

相关文章:

python - 在 Python 中跳出 while 循环

python - 做 "[[' a', 2], ['b' ,1]] + [ ['b' , 2], ['c' , 1]] = [ ['b' , 3], ['a' , 2], 0x1045,67910"的任何 pythonic 方式?

python - 当并非所有值都存在时对列表列表进行排序

Python SocketServer 收不到所有数据

python - 如何定义 "operator()"C++ 类方法的 python pybind11 绑定(bind)?

django - virtualenv 返回错误 'Operation not Permitted'

python - pip 和 easy_install 安装 python 包的麻烦

python 套接字服务器超时

Python socketserver不同的任务

python - 为什么我的Node.js gRPC客户端需要3秒才能将请求发送到Python gRPC服务器?