使用python實現一個簡單的http服務器


 1 import socket
 2 
 3 
 4 class MyServer:
 5     def __init__(self, ip, port):
 6         self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
 7         self.socket.bind((ip,port))    # 綁定的IP和端口
 8         self.socket.listen(128)
 9 
10     def run_forever(self):
11         while True:
12             client_cocket,client_addr = self.socket.accept()  # 獲取http請求head及來源地址
13             data = client_cocket.recv(1024).decode("utf8")    # 對收到的信息解碼
14             path = ''
15             if data:
16                 print("data is {}".format(data)) 
17                 print('{}'.format(client_addr))
18                 path = data.splitlines()[0].split(" ")[1]
19                 print("請求的路徑是:{}".format(path))
20 
21             # response head
22             response_head = "HTTP/1.1 200 OK"
23 
24             if path == '/login':
25                 response_body = "this is login path"
26             elif path == "/logout":
27                 response_body = "you will logout"
28             elif path == "/":
29                 response_body = "welcome to index"
30             else:
31                 response_head = "HTTP/1.1 400 page not fund"
32                 response_body = "you want to get page is lossing"
33 
34             response_head += "\n"  # 注意每一行結尾都要有一個空行
35             response_head +=  "content-type: text/html; charset=UTF-8\n\n" # 注意這里最后還要有一個空行
36             response_body += "\n"
37             
38             response = head + response_body  # 拼接響應報文
39             client_cocket.send(response.encode("utf8"))  # 發送響應報文
40             
41 server = MyServer("0.0.0.0",9090)  # 0.0.0.0表示任何IP地址都可以請求到服務
42 server.run_forever()

 


免責聲明!

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



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