1. 程式人生 > 實用技巧 >使用python實現一個簡單的http伺服器

使用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()