基于BaseHTTPServer的双HTTP和HTTPS Python服务器未按预期工作

基于BaseHTTPServer的双HTTP和HTTPS Python服务器未按预期工作,python,http,https,basehttpserver,Python,Http,Https,Basehttpserver,我正在尝试在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_s

我正在尝试在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端口发送请求时(例如
curlhttp://localhost:1044/path
)它可以工作。但是,当我向HTTPS端口发送请求时(例如
curl-khttps://localhost:11104/path
)服务器从不响应,即curl终端被挂起

我观察到,如果我对启动HTTP服务器的行进行注释(即
httpd.server\u forever()
),则HTTPS服务器可以工作<代码>curl-khttps://localhost:11104/path有效。因此,我猜我做错了什么,这就排除了不能同时设置两台服务器的可能性


感谢您的帮助

根据反馈意见,我以多线程的方式重构了代码,现在它可以正常工作了

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)

可能是因为https的输入错误?localhsott我的问题帖子中有一个输入错误(现已修复),但在实际测试中,我正确地使用了“localhost”。谢谢你的反馈!嗯…在关机之前,永远一次处理一个请求,所以如果你想一次处理一次http和https。试着用不同的思路来做。谢谢@M.Leung!多线程一直是解决这个问题的关键;)在我的Ubuntu 16.04 python 2.7上,我使用try start_new_线程(http_server.serve_forever())start_new_线程(https_server.serve_forever()),而1:time.sleep(1)除了键盘中断打印“done”之外,它不能正常工作,因为只有第一个线程似乎工作,即“wheras”永远阻塞。有人能给我一个提示来解决这个问题吗?我怎样才能正确地在注释中添加代码块?为什么http/https协议前缀会从URL中删除?也许注释不是代码块的下注方式。。。你可以考虑编辑你的答案(使用一个编辑标记并把新内容放在下面)。是的,我试过了,但是编辑只允许5分钟。