HTTP靜態WEB服務器

HTTP靜態WEB服務器

HTTP的做用

  • 伯納斯-李在1989年提出了萬維網的基本框架,三個核心概念分別是HTTP協議、URL和HTML。HTTP協議就是瀏覽器和web服務器之間特定的數據傳輸格式。
  • HTTP網絡協議棧由如下幾部分構成,加入安全層的即爲HTTPS協議。
    • 物理層:
    • 數據鏈路層:提供網絡結構
    • 網絡層:IP
    • 傳輸層:TCP
    • (安全層:SSL)
    • 應用層:HTTP
  • 與基於TCP的服務器相比,HTTP服務器特殊之處是接受和發送的內容爲HTTP報文,HTTP報文由三部分構成,Start line、Header、Body。

面向對象的HTTP靜態WEB服務器

import socket, sys, threading

class HttpServer(object):
    '''定義一個HTTP服務器'''
    def __init__(self,port):
        static_web_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        static_web_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        # 可以經過輸入制定端口
        static_web_server.bind(('127.0.0.1', port))
        self.static_web_server = static_web_server

    def start(self):
        # 啓動服務器
        self.static_web_server.listen(128)
        while True:
            client_service, client_ip_port = self.static_web_server.accept()
            # 實現多線程並設置守護
            sub_web_thread = threading.Thread(target=HttpServer.supply_service,
                                              args=(client_service,), daemon=True)
            sub_web_thread.start()

    @staticmethod
    def supply_service(client_service):
        recv_data = client_service.recv(4096)
        # 檢查客戶端提交的請求中是否存在HTTP格式中的資源路徑,若無則關閉鏈接
        try:
            request_path = recv_data.decode('utf-8').split(' ', maxsplit=2)[1]
        except Exception as error:
            client_service.close()
            return
        else:
            # 根目錄返回index頁面
            if request_path == '/':
                request_path = '/index.html'
            # 根據資源路徑製做響應報文併發送
            HttpServer.make_response(request_path, client_service)

    @staticmethod
    def make_response(request_path,client_service):
        # 檢查目錄下是否存在請求頁面,若無返回error頁面
        try:
            with open('static' + request_path, 'rb') as f_obj:
                send_data = f_obj.read()
        except Exception as error:
            response_line = 'HTTP/1.1 404 Not Found\r\n'
            response_header = 'Server:PWS/1.0\r\n'
            with open('static/error.html', 'rb') as f_obj:
                response_body = f_obj.read()
        else:
            # 封裝成HTTP相應格式
            response_line = 'HTTP/1.1 200 OK\r\n'
            response_header = 'Server:PWS/1.0\r\n'
            response_body = send_data
        finally:
            response = (response_line + response_header + '\r\n').encode('utf-8') + response_body
            client_service.send(response)
            client_service.close()


def main():
    # 獲取命令行參數,並判斷是不是正確的端口號

    # 判斷獲取的參數列表是不是兩個item(第一個item是文件名),
    if len(sys.argv) != 2:
        print('Please enter like"python web_server 10086"')
        return

    # 判斷獲取的參數是不是有效的端口號
    if sys.argv[1].isdigit():
        port = int((sys.argv)[1])
        if 1023 < port < 65536:
            web_server = HttpServer(port)
            web_server.start()
        else:
            print('port is invalid.')
            return
    else:
        print('port is invalid.')
        return
# 判斷是不是主程序
if __name__ == '__main__':
    main()

在python文件當前命令行輸入python web_server 10086,瀏覽器就能在http://localhost:10086/index.html中訪問static文件夾下的頁面。html

總結

分步驟逐步開發python

  • 編寫基於TCP的服務器
  • 從請求報文中解析資源路徑,並按HTTP報文格式發送響應報文
  • 函數封裝、類封裝
  • 命令行啓動
相關文章
相關標籤/搜索