我尝试在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服务器的行(即httpd.server_forever()
),那么HTTPS服务器就可以工作,curl -k https://localhost:11104/path
也可以。因此,我想我做了一些错误的事情,这就排除了不能同时设置两个服务器。在
感谢任何帮助!在
根据反馈意见,我以多线程的方式重构了代码,现在它按预期工作。在
相关问题 更多 >
编程相关推荐