Home >Backend Development >Python Tutorial >How to write a simple HTTP server using Python?

How to write a simple HTTP server using Python?

王林
王林forward
2023-05-07 22:25:061810browse

What is http

httpTCP/IP4-layer network protocol. TCPApplication layer protocol.

Well, the 4-layer model is roughly like this:

How to write a simple HTTP server using Python?

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.

httpIt's on the top layer, which is the application layer.

httpHow close is it to us? Even the article you are seeing now uses the httphttpHypertext

It’s hard to understand, it doesn’t matter, just keep reading.

Analysis of http request message and response message format

Through the above introduction, we know that httphttp.

httpThe message consists of 4 parts, namely the starting line, the header line, the blank line and the entity. Split with \r\nCRLF).

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:

How to write a simple HTTP server using Python?

In the output results, >

The request message format is as follows:

How to write a simple HTTP server using Python?

The request line will specify the request method of http, such as: GET, POST, HEAD, etc., URLhttp, 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 httphttp://juejin.cn

How to write a simple HTTP server using Python?

The above is what we requested using the curlhttp://juejin.cnGET/HTTP/1.1, and then It carries three header lines, namely User-Agent, HostAccept.

The response message format is as follows:

How to write a simple HTTP server using Python?

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

How to write a simple HTTP server using Python?

curlhttp://juejin.cn/. Let’s look at it line by line. The response line tells us httpThe 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服务器呢?

我们知道,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请求一下该接口,我们将会得到请求报文了,如下:

How to write a simple HTTP server using Python?

我们得到请求报文后,可以构建一个响应报文发送回去,例如: 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再来测试一下,是可以得到消息的。

How to write a simple HTTP server using Python?

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete