如何编写 python HTTP 服务器来侦听多个端口? [英] How do I write a python HTTP server to listen on multiple ports?

查看:38
本文介绍了如何编写 python HTTP 服务器来侦听多个端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?

我现在在做什么:

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

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): 
    pass

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

推荐答案

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

Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both http://localhost:1111/ and 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,但需要稍微更改三行:

This also works with Python 3 but three lines need to be slightly changed:

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

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

这篇关于如何编写 python HTTP 服务器来侦听多个端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆