You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS下ThreadingHTTPServer停止接受套接字问题求助

macOS 12.6.2 + Python 3.10.7下ThreadingHTTPServer连接阻塞问题

问题现象

  • 运行环境:macOS 12.6.2,Python 3.10.7(python.org官方分发版本)
  • 异常表现:基于ThreadingHTTPServer实现的代理服务器运行1-2小时后,彻底停止接受新连接
  • 排查结果:
    • 执行lsof -T fqs查看,服务器套接字的监听队列已满,QLEN(未被接受的已建立入站连接数)随时间逐步增长
    • 通过spindump分析进程,主线程超过99.5%的时间处于select_poll_poll -> poll状态,偶尔会退出poll调用,这符合socketserver.BaseServer.serve_forever的循环逻辑(每次selector.select成功返回时仅处理一个套接字)

怀疑方向

  • 问题可能源于macOS系统的poll()函数(此前有相关问题案例)
  • 也可能是Python在macOS平台上对服务器套接字使用poll()的方式存在异常

代码实现

代理服务器基于原生ThreadingHTTPServer搭建,请求处理逻辑运行在独立线程:

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class ProxyHandler(BaseHTTPRequestHandler):
    def do_CONNECT(self): ...
    def do_other(self): ...
    do_GET = do_other
    do_POST = do_other
    do_PUT = do_other
    do_DELETE = do_other
    do_PATCH = do_other
    do_OPTIONS = do_other

server = ThreadingHTTPServer(("0.0.0.0", 8881), ProxyHandler)
print("Serving on %s:%d" % server.server_address)
try:
    server.serve_forever()
except KeyboardInterrupt:
    print("Caught Ctrl+C, exiting...")

server.server_close()

注:do_CONNECT和do_other的具体实现已省略,二者运行在独立线程,理论上不会对主线程造成影响

内容的提问来源于stack exchange,提问作者nneonneo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:45:37