手寫走通HTTP server
阿新 • • 發佈:2018-09-17
int clas 靜態 sockfd split tin itl sets exceptio
HTTP server 2.0
1 接收客戶請求
2 解析客戶端請求
3 組合數據,形成HTTP response
4 將數據發送給客戶端
升級 :
1 多線程接收客戶端請求
2 基本的請求解析,根據請求返回數據(相應內容)
3 除了可以請求靜態網頁,也可以請求簡單的數據
4 將功能封裝在一個類中
#coding = utf-8 ‘‘‘http 2.0 1多線程並發 2可以請求簡單數據 3能進行簡單請求解析 4結構使用類進行封裝 ‘‘‘ import socket, os, sys, traceback from threading import Thread#封裝具體的服務器功能 class HTTPserver(object): def __init__(self,server_addr,server_static_dir): self.server_addr = server_addr self.server_static_dir = server_static_dir self.ip = server_addr[0] self.port = server_addr[1] self.create_socket()def create_socket(self):#創建 self.sockfd = socket.socket() self.sockfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sockfd.bind(self.server_addr) def serve_forever(self):#啟動 self.sockfd.listen() print(‘listen the prot:%s‘ % self.port)while True: try: confd, addr = self.sockfd.accept() except KeyboardInterrupt: self.sockfd.close() sys.exit(‘服務器退出‘) except Exception: traceback.print_exc() continue # 創建新的線程處理請求 t = Thread(target=self.handle, args=(confd,)) t.Daemon = True t.start() def handle(self, confd): # 接收客戶端請求 data = confd.recv(1024) # 解析請求內容 dataHeader = data.splitlines() # 獲取具體請求內容 getRequest = str(dataHeader[0]).split(‘ ‘)[1] urls = [‘/‘,‘/index‘,‘/index_1‘,‘/index_2‘] if getRequest == ‘/‘ or getRequest[-5:] == ‘.html‘:#獲取主頁 print(‘已進行來‘) self.get_html(confd) elif getRequest in urls: #獲取下級頁面 self.get_data(confd,getRequest) else: self.error_(confd) confd.close() def get_data(self, confd,getReques):#獲取頁面數據 getReques = getReques.split(‘/‘)[1] path =os.path.join(self.server_static_dir,getReques) print(path) with open(path+‘.html‘,‘r‘) as f: data = f.read() response = ‘HTTP/1.1 200 OK\r\n‘ response +=‘\r\n‘ response +=data confd.send(response.encode()) def error_(self,confd):#出錯處理 response = ‘HTTP/1.1 404 NOT FUOUND\r\n‘ response += ‘\r\n‘ responseBOdy = ‘SORRY,NOT PAGE‘ response += responseBOdy confd.send(responseBOdy.encode()) def get_html(self,confd):#首頁處理 with open(‘index.html‘,‘r‘) as f: data = f.read() #print(data) xieyi = ‘HTTP/1.1 200 OK \r\n‘ xieyi += ‘\r\n‘ xieyi += data confd.send(xieyi.encode()) if __name__ == ‘__main__‘: server_addr = (‘127.0.0.1‘, 8080)#地址 server_static_dir = os.getcwd()#靜態頁面目錄 #生成對象 httpd = HTTPserver(server_addr, server_static_dir) #啟動服務器 httpd.serve_forever()
手寫走通HTTP server