Skip to content

ConnectionError

错误信息

                ConnectionError: [Errno 111] 连接 refused
              

快速摘要

network 连接能 不是 established or 是 lost — 服务器可能是 下 or unreachable.

为什么发生

  • 服务器是 不运行 or 是下

  • 错误 host or port 数字

  • Network firewall blocking 连接

  • 连接是 reset 通过 remote host

最小示例

✗ 错误代码
import socket
s = socket.socket()
s.connect(('localhost', 9999))  # ConnectionError if nothing is listening
✓ 修复代码
import socket
try:
    s = socket.socket()
    s.connect(('localhost', 9999))
except ConnectionError as e:
    print(f"Connection failed: {e}")
    s = None

Wrap 连接 in try/except ConnectionError 到 handle 服务器那个是 下 or unreachable.

如何诊断

  • 验证服务器是 运行 and port 是正确

  • 检查 network connectivity (ping host)

  • Look for firewall 规则 blocking 连接

如何修复

  • 开始服务器 or use 正确 host/port

  • Implement retry logic 使用 exponential backoff

  • Use try/except ConnectionError 到 handle failures

  • 检查 firewall and network 配置

如何预防

  • Implement 连接 retry logic

  • Use 连接 pooling 使用 timeouts

  • 验证 host and port 之前连接

相关资源

相关术语

相关课程

← 返回语言