python實現web服務器

發送單個文件

瀏覽器使用http://localhost:8080訪問

import socket
 
server_html=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 
server_html.bind(("127.0.0.1",8080))
 
server_html.listen(10)
 
while True:
 
    client,addr=server_html.accept()
    msg=client.recv(1024*12)
    print(client)
    #以字節讀取數據的權限去打開html_pro.html文件
    file_html=open("html/capture.html","rb")
    #讀取文件內容
    data=file_html.read()
    #下面這句話必須寫,關於http協議的內容,以後說
    response_headers = "HTTP/1.1 200 OK\r\n" # 200 表示找到這個資源
    response_headers += "\r\n" # 空一行與body隔開
    client.sendall(bytes(response_headers,"utf-8")) 
    #發送讀取的內容
    client.sendall(data)
    client.close()
    
if __name__ == '__main__':
    main()

web服務器其

from socket import *
 
def handle_client(client_socket):
    """爲一個客戶端服務"""
    # 接收對方發送的數據
    recv_data = client_socket.recv(1024).decode("utf-8") #  1024表示本次接收的最大字節數
    # 打印從客戶端發送過來的數據內容
    #print("client_recv:"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章