如何编写一个 python HTTP 服务器来监听多个端口? 您所在的位置:网站首页 端口api 如何编写一个 python HTTP 服务器来监听多个端口?

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

#如何编写一个 python HTTP 服务器来监听多个端口?| 来源: 网络整理| 查看: 265

当然,只要在两个不同的线程中,在两个不同的端口启动两个不同的服务器,各自使用同一个处理程序。 这是一个完整的、可以工作的例子,我刚刚写好并进行了测试。 如果你运行这段代码,那么你就能在两个地方得到一个Hello World的网页http://localhost:1111/和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"))


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有