I’m structuring a web server (…), aiming to interpret the python language (just like apache does with php ). I establish the connection (client x server) in the transport layer through the TCP protocol using python’s socketserver module. Now I need to capture the request header data and send an http response to the client (browser), how could I do that? Below is the code and result of the processing:
File : 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
We noticed that the output of the process has the http header, now I need to capture the data without using http.server as it is not recommended for the production environment. How could I get the request method, path, host and answer the request to the browser?