简体   繁体   English

基于BaseHTTPServer的双HTTP和HTTPS Python服务器无法正常工作

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

I'm trying to implement a Python server supporting both HTTP and HTTPS based in BaseHTTPServer. 我正在尝试在BaseHTTPServer中实现同时支持HTTP和HTTPS的Python服务器。 This is my code: 这是我的代码:

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()

So, HTTP runs in port 1044 and HTTPS runs in 11044. The MyHandler class is omitted for the sake of briefness. 因此,HTTP在端口1044中运行,而HTTPS在11044中运行。为简洁起见,省略了MyHandler类。

Using that code, when I send requests to HTTP port (eg curl http://localhost:1044/path ) it works. 使用该代码,当我向HTTP端口发送请求时(例如curl http://localhost:1044/path ),它可以工作。 However, when I send requests to the HTTPS port (eg curl -k https://localhost:11104/path ) the server never responses, ie the curl terminal gets hanged. 但是,当我将请求发送到HTTPS端口(例如curl -k https://localhost:11104/path )时,服务器从不响应,即curl终端被挂起。

I have observed that if I comment the line starting the HTTP server (ie httpd.server_forever() ) then the HTTPS server works,.ie curl -k https://localhost:11104/path works. 我观察到,如果我注释启动HTTP服务器的行(即httpd.server_forever() ),则HTTPS服务器可以工作,即curl -k https://localhost:11104/path可以工作。 Thus, I guess that I'm doing something wrong which is precluding not being able to set both servers at the same time. 因此,我想我做错了什么,就是不能同时设置两个服务器。

Any help is appreciated! 任何帮助表示赞赏!

Following feedback comments, I have refactored the code in a multithread way and now it works as expected. 根据反馈意见,我以多线程方式重构了代码,现在它可以按预期工作。

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