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

2024-09-29 23:15:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在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也可以。因此,我想我做了一些错误的事情,这就排除了不能同时设置两个服务器。在

感谢任何帮助!在


Tags: path端口https服务器localhosthttpserversocket
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:36

根据反馈意见,我以多线程的方式重构了代码,现在它按预期工作。在

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)

相关问题 更多 >

    热门问题