簡體   English   中英

基於BaseHTTPServer的雙HTTP和HTTPS Python服務器無法正常工作

[英]Dual HTTP and HTTPS Python server based on BaseHTTPServer not working as expected

我正在嘗試在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可以工作。 因此,我想我做錯了什么,就是不能同時設置兩個服務器。

任何幫助表示贊賞!

根據反饋意見,我以多線程方式重構了代碼,現在它可以按預期工作。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM