首页 > 解决方案 > 使用 socketserver 处理 http 协议

问题描述

使用 socketserver 处理 http 协议

我正在构建一个 Web 服务器(...),旨在解释 Python 语言(就像 apache 对 php 所做的那样)。我使用python的socketserver模块通过TCP协议在传输层建立连接(客户端x服务器)。现在我需要捕获请求头数据并向客户端(浏览器)发送一个 http 响应,我该怎么做呢?下面是处理的代码和结果:

文件:httptcpipv4.py

# Module Name : socketserver -> https://docs.python.org/3/library/socketserver.html#module-socketserver
from socketserver import BaseRequestHandler, ThreadingTCPServer


# Transport Layer Protocol : TCP
# This is the superclass of all request handler objects. It defines the interface, given below.
class HTTPTCPIPv4(BaseRequestHandler):
    
    def handle(self):
        
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).decode()
        print(self.data)


if __name__ == "__main__":
    HOST, PORT = "", 8080

    # Create the asynchronous server, binding to localhost on port 8080
    with ThreadingTCPServer((HOST, PORT), HTTPTCPIPv4) as server:
        print("Server : Action v0.0.1, running address http://127.0.0.1:8080,")
        print("cancel program with Ctrl-C")
        server.serve_forever()

输出 :

GET / HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"
sec-ch-ua-mobile: ?0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Purpose: prefetch
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7

标签: pythonpython-3.x

解决方案


推荐阅读