我正在尝试基于 BaseHTTPServer 实现支持 HTTP 和 HTTPS 的 Python 服务器。这是我的代码:
server_class = BaseHTTPServer.HTTPServer
# Configure servers
httpd = server_class(("0.0.0.0", 1044), MyHandler)
httpsd = server_class(("0.0.0.0", 11044), MyHandler)
httpsd.socket = ssl.wrap_socket(httpsd.socket, keyfile="/tmp/localhost.key", certfile="/tmp/localhost.crt", server_side=True)
# Run the servers
try:
httpd.serve_forever()
httpsd.serve_forever()
except KeyboardInterrupt:
print("Closing the server...")
httpd.server_close()
httpsd.server_close()
因此,HTTP 运行在 1044 端口,HTTPS 运行在 11044。为了简洁起见,省略了 MyHandler 类。
使用该代码,当我向 HTTP 端口(例如)发送请求时,curl http://localhost:1044/path
它可以工作。但是,当我向 HTTPS 端口(例如curl -k https://localhost:11104/path
)发送请求时,服务器永远不会响应,即 curl 终端被挂起。
我观察到,如果我注释启动 HTTP 服务器 (ie httpd.server_forever()
) 的行,那么 HTTPS 服务器工作,.iecurl -k https://localhost:11104/path
工作。因此,我想我做错了什么,排除了无法同时设置两台服务器。
任何帮助表示赞赏!