gpt4 book ai didi

python - 如何编写一个 python HTTP 服务器来监听多个端口?

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:39 26 4
gpt4 key购买 nike

我正在用 Python 编写一个小型 Web 服务器,使用 BaseHTTPServer 和 BaseHTTPServer.BaseHTTPRequestHandler 的自定义子类。是否可以在多个端口上进行监听?

我现在在做什么:

class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass

server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()

最佳答案

当然;只需在两个不同线程的两个不同端口上启动两个不同的服务器,每个线程都使用相同的处理程序。这是我刚刚编写和测试的完整的、有效的示例。如果您运行此代码,那么您将能够在 http://localhost:1111/ 处获得 Hello World 网页。和 http://localhost:2222/

from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("Hello World!")

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True

def serve_on_port(port):
server = ThreadingHTTPServer(("localhost",port), Handler)
server.serve_forever()

Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)

更新:

这也适用于 Python 3,但需要稍微更改三行:

from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler

self.wfile.write(bytes("Hello World!", "utf-8"))

关于python - 如何编写一个 python HTTP 服务器来监听多个端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com