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協議,三次握手,四次揮手 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM