socket 简单实现HTTP服务器

 1 # -*- coding: utf-8 -*-
 2 # @Time : 2019-07-17 1:39
 3 # @File : 网络socket实现http服务器.py
 4 # @Software: PyCharm
 5 
 6 import socket
 7 import re
 8 
 9 
10 def server_conn(conn,file_name):
11     # 1.响应头部
12     if file_name == '/index.html':
13         # 可换成HTML本地文件
14         response = "HTTP/1.1 200 OK \r\n"
15         # 2.响应body
16         response += "\r\n"
17         response += "<h1> index </h1>"
18         # 3.发送请求
19         conn.sendall(bytes(response, encoding="utf-8"))
20     else:
21         response = "HTTP/1.1 404 OK \r\n"
22         # 2.响应body
23         response += "\r\n"
24         response += "<h1> pages not found </h1>"
25         # 3.发送请求
26         conn.sendall(bytes(response, encoding="utf-8"))
27     pass
28 
29 
30 def main(host, port):
31     # 1.创建套接字
32     server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
33     server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
34     # 2.绑定
35     server.bind((host, port))
36     # 3.监听
37     server.listen(128)
38     # 4.连接
39     while True:
40         conn, address = server.accept()
41         # 接收客户端消息,最大字节数1024
42         client_mess = conn.recv(1024)
43         # 接收浏览器返回数据
44         client_content = str(client_mess, encoding="utf-8").splitlines()
45         # 切割匹配访问路径
46         file_name = re.match(r"[^/]+(/[^ ]*)",client_content[0])
47         if file_name:
48             file_name1 = file_name.group(1)
49             if file_name1 == "/":
50                 file_name1 = "/index.html"
51             print(file_name1)
52         # print(client_content)
53         server_conn(conn,file_name1)
54         conn.close()
55     pass
56 
57 
58 if __name__ == "__main__":
59     main("127.0.0.1", 7890)
60 
61 # 注 : http协议,三次握手,四次挥手 

猜你喜欢

转载自www.cnblogs.com/jum-bolg/p/11198584.html