您好,登錄后才能下訂單哦!
師父布置的任務,讓我寫一個服務練練手,搞清楚socket的原理和過程后跑了一個小demo,很有成就感,代碼內容也比較清晰易懂,很有教育啟發意義。
代碼
# coding:utf-8 import socket from multiprocessing import Process HTML_ROOT_DIR = "" def handle_client(client_socket): """處理客戶端請求""" # 獲取客戶端請求數據 request_data = client_socket.recv(1024) print("request data:", request_data) # 構造響應數據 response_start_line = "HTTP/1.1 200 OK\r\n" response_headers = "Server: My server\r\n" response_body = "hello itcast" response = response_start_line + response_headers + "\r\n" + response_body print("response data:", response) # 向客戶端返回響應數據 client_socket.send(bytes(response, "utf-8")) # 關閉客戶端連接 client_socket.close() if __name__=="__main__": server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 8000)) server_socket.listen(120) while True: client_socket, client_address = server_socket.accept() # print("[%s, %s]用戶連接上了"%client_addrest[0],client_address[1]) print("[%s, %s]用戶連接上了" % client_address) handle_client_process = Process(target=handle_client, args=(client_socket,)) handle_client_process.start() client_socket.close()
運行后在瀏覽器輸入:127.0.0.1:8000
http頁面顯示如下:
控制臺輸出:
[127.0.0.1, 50066]用戶連接上了 request data: b'GET / HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nUpgrade-Insecure-Requests: 1\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5\r\nAccept-Language: zh-cn\r\nAccept-Encoding: gzip, deflate\r\nConnection: keep-alive\r\n\r\n' response data: HTTP/1.1 200 OK Server: My server hello itcast [127.0.0.1, 50067]用戶連接上了 request data: b'GET /favicon.ico HTTP/1.1\r\nHost: 127.0.0.1:8000\r\nConnection: keep-alive\r\nAccept: */*\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5\r\nAccept-Language: zh-cn\r\nReferer: http://127.0.0.1:8000/\r\nAccept-Encoding: gzip, deflate\r\n\r\n' response data: HTTP/1.1 200 OK Server: My server hello itcast
以上這篇使用python 寫一個靜態服務(實戰)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。