桓楠百科网

编程知识、经典语录与百科知识分享平台

PYTHON多线程实现web服务器httpserver实例

PYTHON多线程实现web服务器

import http.server
import socketserver
import threading

# 服务器监听的端口
PORT = 8000

# 创建支持多线程的 HTTP 服务器类
class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    pass

# 自定义请求处理程序
class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 发送 200 状态码,表示请求成功
        self.send_response(200)
        # 设置响应头,指定内容类型为纯文本
        self.send_header('Content-type', 'text/plain')
        # 结束响应头的设置
        self.end_headers()
        # 要返回的消息
        message = "Hello World "
        # 将消息编码为字节流并发送给客户端
        self.wfile.write(message.encode())


Handler = CustomHandler

with ThreadedHTTPServer(("", PORT), Handler) as httpd:
    print(f"Serving at port {PORT}")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print("Server stopped.")
    

运行python程序

D:\code\python\http>python dxc0.py
Serving at port 8000

运行结果

D:\code\cpp\xc>curl http://127.0.0.1:8000
Hello World
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言