我正在尝试在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
),服务器永远不会响应,即卷曲终端被挂起。
我观察到如果我评论启动HTTP服务器的行(即httpd.server_forever()
),则HTTPS服务器工作,.i.e。 curl -k https://localhost:11104/path
有效。因此,我猜我做错了,这使得无法同时设置两台服务器。
感谢任何帮助!
答案 0 :(得分:0)
根据反馈意见,我以多线程的方式重构了代码,现在它按预期工作。
def init_server(http):
server_class = BaseHTTPServer.HTTPServer
if http:
httpd = server_class(("0.0.0.0", 1044), MyHandler)
else: # https
httpd = server_class(("0.0.0.0", 11044), MyHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, keyfile="/tmp/localhost.key", certfile="/tmp/localhost.crt", server_side=True)
httpd.serve_forever()
httpd.server_close()
VERBOSE = "True"
thread.start_new_thread(init_server, (True, ))
thread.start_new_thread(init_server, (False, ))
while 1:
time.sleep(10)