python / 练习级源码 · 02/20/2023 0

python 静态服务器

import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind("",9090)
s.listen(128)
#接收http请求,解析请求地址,然后再把网页内容组诚http报文发回去。下面是接收
while True:
    nc,np = s.accept()
    recv_data = nc.recv(4096)
    if len(recv_data) == 0:
        nc.close()
        return
    recv_content = recv_data.decode('utf-8')
    print(recv_content)

#把数据按空格分割 只选取http报文的第二段re_list[1]即它的请求路径文件
    re_list = recv_content.split("",maxsplit=2)
    re_path = re_list[1]
    print(re_path)

    if re_path == "/":
        re_path ="/index.html"
#组诚发送报文http格式.
    with open("static" + re_path,"rb") as file:
        file_data = file.read()

        response_line = "HTTP/1.1 200 OK\r\n"
        response_header = "Server: POCO/1.r\n"
        response_body = file_data
        response = (response_line+response_header+"\r\n").encode('utf-8')+response_body
#发送很简单
        nc.send(response)