Home > Article > Backend Development > How to write a simple HTTP server using Python?
http
TCP/IP4-layer network protocol. TCP
Application layer protocol.
Well, the 4-layer model is roughly like this:
In network communication, user data is transmitted in messages, but in actual During communication, each layer will encapsulate the packet to form segments, datagrams, and frames, and finally transmit it as a bit stream (binary). After arriving at the target host, each layer will be disassembled to obtain The final message.
http
It's on the top layer, which is the application layer.
http
How close is it to us? Even the article you are seeing now uses the http
httpHypertext
It’s hard to understand, it doesn’t matter, just keep reading.
Through the above introduction, we know that http
http.
http
The message consists of 4 parts, namely the starting line, the header line, the blank line and the entity. Split with \r\n
CRLF).
Let’s take a look at the actual message.
In linux
, we can use curl -v URL
Command:
curl -v http://juejin.cn
Request information:
In the output results, >
The request message format is as follows:
The request line will specify the request method of http
, such as: GET
, POST
, HEAD
, etc., URL
http, and finally End with CRLF
.
There can be multiple header lines, which appear in the form of (field name: value). Each header line also ends with CRLF
.
Then there is a blank line. A blank line represents the end of the http
http://juejin.cn
The above is what we requested using the curl
http://juejin.cnGET/HTTP/1.1, and then It carries three header lines, namely User-Agent
, Host
Accept.
The response message format is as follows:
Comparing the response message and the request message, it is not difficult to find that except for the first line, other The format is the same, so we only introduce the information of the response line. In the response line, the first one is the protocol version, which is the protocol version of the server, and then the status code is used to inform the client. The server's response information ends with a phrase. The function of the phrase is to inform the user what the returned information probably means.
Okay, let’s fill in the above message sent to us by juejin.cn
curlhttp://juejin.cn/. Let’s look at it line by line. The response line tells us http
The version is HTTP/1.1
, the status code is 301
, and the phrase is the link has been transferred.
If we only use the status code above, it is difficult to get
首部行,告知了我们服务器 、时间 、 报文类型 以及 报文长度。还记得我们第一段落介绍过得,http
现在除了发送超文本以外,还可以发送图片、视频等,就是通过首部行Content-Type
来确定的。
接着是空白行,最后是报文主体,哎,有没有感觉奇怪呢?为什么请求报文主体是空的呢?这是因为报文主体长度是由首部行Content-Length
来定义的,如上报文展示的是,我们报文主体有262个字符。
上述,我们介绍了,什么是http
以及初略的看了一下 http
的请求报文和响应报文,那么,我们如何构建一个http
服务器呢?
我们知道,http
是应用层协议,是基于传输层tcp
来实现的,所以,我们若想构建一个http
服务器,那么应该写一个socket
程序出来吧。
import socket import threading def handle(client , addr): print("from " , addr) data = client.recv(1024) for k,v in enumerate(data.decode().split("\r\n")): print(k ,v) def main(): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind(("127.0.0.1",8080)) s.listen() while True: client , addr = s.accept() t = threading.Thread(target=handle,args=(client,addr)) t.start() if __name__ == '__main__' main()
上述,我们写了一个tcp
程序,它将监听本地回环地址的8080
端口,若此时我们使用curl -v 127.0.0.1:8080
请求一下该接口,我们将会得到请求报文了,如下:
我们得到请求报文后,可以构建一个响应报文发送回去,例如: Hello, Destined Person.
,我们就可以这样来构建http
import socket import threading def handle(client , addr): print("from " , addr) data = client.recv(1024) #请求报文 for k,v in enumerate(data. decode() .split("\r\n")): print(k ,v) bodyText = "He1lo,Destined Person." #响应报文 #响应行 client.send(b"HTTP/1.1 200 OK\r\n") #首部行 client. send(b"Server: pdudo_web_sites\r\n") client. send(b"Content-Type: text/html\r\n") client. send(("Content-Length: %s\r\n" % (len(bodyText) + 2)).encode()) client. send(b"\r\n") client. send(("%s\r\n" %(bodyText)).encode()) def main(): try: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s .bind(("127.0.0.1"8080)) s .listen() while True: client,addr = s.accept() t = threading.Thread(target=handle,args=(client,addr)) t.start() finally: s.close() if __name__ == '__main__': main()
最后我们使用curl
再来测试一下,是可以得到消息的。
The above is the detailed content of How to write a simple HTTP server using Python?. For more information, please follow other related articles on the PHP Chinese website!