0

我正在尝试基于 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工作。因此,我想我做错了什么,排除了无法同时设置两台服务器。

任何帮助表示赞赏!

4

1 回答 1

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)
于 2017-06-20T11:43:23.430 回答