python3實(shí)現(xiàn)微型的web服務(wù)器
實(shí)驗(yàn)?zāi)康模?/strong>用socket 模擬一個(gè)微型的web服務(wù)器,當(dāng)py腳本run起后,實(shí)微型web server架起了,然后用本地瀏覽器訪問127.0.0.1:8080(web server的ip_port)時(shí)web服務(wù)器就會(huì)將網(wǎng)頁內(nèi)容傳給瀏覽器,實(shí)現(xiàn)網(wǎng)頁瀏覽.
sw+sys: python3.7.2 + windows10 64bit
本地準(zhǔn)備的server端網(wǎng)頁為下載的hao123主頁(我已上載并上傳,點(diǎn)擊這里)
通過這個(gè)實(shí)驗(yàn)讓我學(xué)到了:
1. 當(dāng)get請(qǐng)求一個(gè)主頁時(shí),要完整的顯示一個(gè)頁面(包括文本、圖片、css絢染等)是要get多次請(qǐng)求的。
2. respone回復(fù)本地頁網(wǎng),open(filepath, rwa)時(shí)要特別的注意
import socket import os curfilepath = os.path.split(os.path.realpath(__file__))[0].replace("\\" , "/") print(f'curfilepath: {curfilepath}') def new_socket_server(new_socket, new_addr): if new_addr[0] != '': print(f'當(dāng)前客戶端{(lán)new_addr}已連接上server端. ') # 3.接收信息 file_name = '' request_data = new_socket.recv(1024).decode('utf-8') if request_data != '': print(f'有收到新的信息,信息如下:\n{request_data}') file_name = request_data.splitlines()[0].split(' ')[1] print(f'file_name: {file_name}') if file_name == '/': file_name = '/index.html' print(f'file_name: {file_name}') with open(curfilepath + '/test.txt', 'a+') as f: f.write(file_name + '\n') # 4.回復(fù)信息 try: f = open(curfilepath + '/htmltest' + file_name, 'rb') except: response = 'HTTP/1.1 404 NOT FOUND\r\n' response += '\r\n' response += '----------file not found-------' new_socket.send(response.encode('utf-8')) else: html_content = f.read() f.close() response = 'HTTP/1.1 200 OK\r\n' + '\r\n' new_socket.send(response.encode('utf-8')) new_socket.send(html_content) def main(): # 1.創(chuàng)建socket tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2.連接server server_ip_port = ('127.0.0.1', 8080) tcp_server_socket.bind(server_ip_port) tcp_server_socket.listen(128) while True: print('正在等待client端連接... ...') new_socket, new_addr = tcp_server_socket.accept() new_socket_server(new_socket, new_addr) new_socket.close() if __name__ == '__main__': main()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python實(shí)時(shí)監(jiān)控網(wǎng)站瀏覽記錄實(shí)現(xiàn)過程詳解
這篇文章主要介紹了Python實(shí)時(shí)監(jiān)控網(wǎng)站瀏覽記錄實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07保姆級(jí)官方y(tǒng)olov7訓(xùn)練自己的數(shù)據(jù)集及項(xiàng)目部署詳解
最近使用了YOLOv7訓(xùn)練自己的數(shù)據(jù)集,接下來簡(jiǎn)單記錄一下項(xiàng)目的部署,這篇文章主要給大家介紹了關(guān)于保姆級(jí)官方y(tǒng)olov7訓(xùn)練自己的數(shù)據(jù)集及項(xiàng)目部署的相關(guān)資料,需要的朋友可以參考下2022-08-08python使用super()出現(xiàn)錯(cuò)誤解決辦法
這篇文章主要介紹了python使用super()出現(xiàn)錯(cuò)誤解決辦法的相關(guān)資料,對(duì)于TypeError: must be type, not classobj的錯(cuò)誤進(jìn)行處理,需要的朋友可以參考下2017-08-08解決python測(cè)試opencv時(shí)imread導(dǎo)致的錯(cuò)誤問題
今天小編就為大家分享一篇解決python測(cè)試opencv時(shí)imread導(dǎo)致的錯(cuò)誤問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-01-01Python使用多進(jìn)程運(yùn)行含有任意個(gè)參數(shù)的函數(shù)
這篇文章主要介紹了Python使用多進(jìn)程運(yùn)行含有任意個(gè)參數(shù)的函數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05