Python 實現(xiàn)一個簡單的web服務(wù)器
import reimport socketdef service_cilent(new_socket): request = new_socket.recv(1024).decode('utf-8') # Python splitlines() 按照行(’r’, ’rn’, n’)分隔,返回一個包含各行作為元素的列表,如果參數(shù) keepends 為 False,不包含換行符,如果為 True,則保留換行符。 request_lines = request.splitlines() print(request_lines) file_name = '' ret = re.match(r'[^/]+(/[^ ]*)', request_lines[0]) if ret: file_name = ret.group(1) if file_name == '/': file_name = 'index.html' try: f = open(file_name, 'rb') except: response = 'HTTP/1.1 404 NOT FOUNDrnrn' response += '------file not found-----' new_socket.send(response.encode('utf-8')) else: # 打開文件成功就讀文件 然后關(guān)閉文件指針 html_content = f.read() f.close() # 準(zhǔn)備發(fā)送給瀏覽器的數(shù)據(jù)---header response = 'HTTP/1.1 200 OKrnrn' # 將response header發(fā)送給瀏覽器 new_socket.send(response.encode('utf-8')) # 將response body發(fā)送給瀏覽器 new_socket.send(html_content) # 關(guān)閉套接字 new_socket.close()def main(): # 創(chuàng)建套接字 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 綁定 tcp_server_socket.bind(('', 7089)) # 監(jiān)聽套接字 tcp_server_socket.listen(128) while True: new_socket, cilent_addr = tcp_server_socket.accept() service_cilent(new_socket) # 關(guān)閉監(jiān)聽套接字 tcp_server_socket.close()if __name__ == ’__main__’: main()
以上就是Python 實現(xiàn)一個簡單的web服務(wù)器的詳細(xì)內(nèi)容,更多關(guān)于python 實現(xiàn)web服務(wù)器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. JS中6個對象數(shù)組去重的方法2. Java commons-httpclient如果實現(xiàn)get及post請求3. 資深程序員:給Python軟件開發(fā)測試的25個忠告!4. 一文帶你徹底理解Java序列化和反序列化5. PHP程序員簡單的開展服務(wù)治理架構(gòu)操作詳解(二)6. PHP利用curl發(fā)送HTTP請求的實例代碼7. Python基于requests庫爬取網(wǎng)站信息8. vscode運行php報錯php?not?found解決辦法9. PHP laravel實現(xiàn)導(dǎo)出PDF功能10. python中文本字符處理的簡單方法記錄

網(wǎng)公網(wǎng)安備