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/60680/

相关文章:

php - 有人可以解释一下缓存动态 PHP 页面吗?

python - Flask RestPlus : how to catch all exceptions and output the original error

python - 这行代码中的[0]是什么意思?

python - PyCharm 在 vi​​rtualenv 中找不到包

带矩阵的 Python 回归

node.js - 使用 Node.js、express 和 mongoDB 时,CURL 中的服务器错误回复为空

c++ - 每个 cpp 的 nginx 语法高亮显示,无需人工交互

java - RFC 2388 多部分 POST 的服务器实现与 RFC 2047 冲突?

python - 将 csv 文件读取到 python ValueError : could not convert string to float

nginx - nginx web服务器支持哪种服务器端语言