python 編寫簡單網頁服務器的實例
更新時間:2018年06月01日 15:05:25 作者:煙雨流年
今天小編就為大家分享一篇python 編寫簡單網頁服務器的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
IDE:Pycharm
sever.py
#!/bin/python #-*- coding: UTF-8 -*- #文件名:server.py #create by wzh 2017/10/26 import socket #導入socket模塊 import re from multiprocessing import Process #導入進程模塊 #設置靜態(tài)文件根目錄 HTML_ROOT_DIR='./html' def handle_client(client_socket): """處理客戶端連接請求""" request_data=client_socket.recv(1024) print(request_data) request_lines=request_data.splitlines() for line in request_lines: print(line) #'GET / HTTP/1.1' request_start_line=request_lines[0].decode("utf-8") print("*"*10) print(request_start_line) #提取用戶請求的文件名 file_name=re.match(r"\w+ +(/[^ ]*) ",str(request_start_line)).group(1) if "/" == file_name: file_name='/index.html' #打開文件,讀取內容 try: file=open(HTML_ROOT_DIR+file_name,"rb") except IOError: response_start_line="HTTP/1.1 404 Not Found\r\n" response_heads="Server: My server\r\n" response_body="The file not found!" else: file_data=file.read() file.close() response_start_line="HTTP/1.1 200 ok\r\n" response_heads="Server: My server\r\n" response_body=file_data.decode("utf-8") response=response_start_line+response_heads+"\r\n"+response_body print("response data:",response) client_socket.send(bytes(response,"utf-8")) client_socket.close() if __name__=="__main__": #如果直接運行本文件,那么__name__為__main__(此時才運行下面的程序),否則為對應包名 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 創(chuàng)建socket對象 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #host = socket.gethostname() # 獲取本地主機名 port = 1212 # #print(host) s.bind(("", port)) # 綁定端口 s.listen(5) while True: c,addr=s.accept() #建立客戶端連接 print('連接地址',addr) handle_client_process=Process(target=handle_client,args=(c,)) #ALT+ENTER快捷鍵生成函數 handle_client_process.start() c.close()
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Web</title> </head> <h1 align="center">welcome!</h1> <p align="center">這是一個神奇的網站!</p> <body> </body> </html>
運行server.py
在瀏覽器中輸入localhost:1212
以上這篇python 編寫簡單網頁服務器的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
pip 20.3 新版本發(fā)布!即將拋棄 Python 2.x(推薦)
這篇文章主要介紹了pip 20.3 新版本發(fā)布!即將拋棄 Python 2.x,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12python可視化分析的實現(matplotlib、seaborn、ggplot2)
這篇文章主要介紹了python可視化分析的實現(matplotlib、seaborn、ggplot2),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02Python數據分析:手把手教你用Pandas生成可視化圖表的教程
今天小編就為大家分享一篇Python數據分析:手把手教你用Pandas生成可視化圖表的教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python網絡請求模塊urllib與requests使用介紹
網絡爬蟲的第一步就是根據URL,獲取網頁的HTML信息。在Python3中,可以使用urllib和requests進行網頁數據獲取,這篇文章主要介紹了Python網絡請求模塊urllib與requests使用2022-10-10