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

标签 python webserver

我正在用 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/

相关文章:

python - MongoEngine:Embeddeddocument 字段不将默认值设置为 none?

没有网络服务器的 mysql 访问(例如 Apache)

Java/Android - 快速 ByteBuffer 解析

performance - MarkLogic 服务器可以处理多少个并发连接?

ruby-on-rails-3 - unicorn 与 Heroku 竹栈

mysql - CD 中的 Uwamp Mysql Server 在 5 秒后停止运行

python - 如何使用 JIRA python API 将观察者添加到 JIRA 票证

python - 使用数据框中的条件删除重复项

python - 在 KDE 上为 Python 导入 Gtk 类型库

python - 删除另一个列表中列表中的第二个值