python高级学习笔记Day02--python静态Web服务器的搭建

开发自己静态Web服务器

python高级学习笔记Day02--python静态Web服务器的搭建_第1张图片

pycharm打开包含服务器资源(html文件,图片资源等)的文件夹,创建新py文件

代码如下:

 import socket

if __name__ == '__main__':
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind(('', 8080))
    tcp_server_socket.listen(128)
    while True:
        client_socket, client_ip = tcp_server_socket.accept()
        client_request_data = client_socket.recv(1024).decode()
        print(client_request_data)
        with open('./index.html', 'rb') as fp:
            file_data = fp.read()
        response_line = 'HTTP/1.1 200 OK \r\n'
        response_header = 'Server:pwb\r\n'
        response_body = file_data
        response_data = (response_line + response_header + '\r\n').encode() + response_body
        client_socket.send(response_data)
        client_socket.close()

函数说明:setsockopt()用来设置参数s 所指定的socket 状态. 参数level 代表欲设置的网络层, 一般设成SOL_SOCKET 以存取socket 层   

SO_REUSEADDR 允许在bind ()过程中本地地址可重复使用

静态Web服务器升级版本(多任务,解决访问文件不存在等报错问题)

import socket
import threading


def handle_client(client_socket):
    client_request_data = client_socket.recv(1024).decode()
    if len(client_request_data)==1:
        client_socket.close
        return
    requestspath = client_request_data.split(' ')[1]
    if requestspath == '/':
        requestspath = '/index.html'
    try:
        with open('.' + requestspath, 'rb') as fp:
            file_data = fp.read()
    except Exception as e:
        response_line = 'HTTP/1.1 404 Not Found \r\n'
        response_header = 'Server:pwb\r\n'
        response_body = "404 Not Found"
        response_data = (response_line + response_header + '\r\n' + response_body).encode()
        client_socket.send(response_data)
    else:
        response_line = 'HTTP/1.1 200 OK \r\n'
        response_header = 'Server:pwb\r\n'
        response_body = file_data
        response_data = (response_line + response_header + '\r\n').encode() + response_body
        client_socket.send(response_data)
    finally:
        client_socket.close()


if __name__ == '__main__':
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind(('', 8080))
    tcp_server_socket.listen(128)
    while True:
        client_socket, client_ip = tcp_server_socket.accept()
        client_thread = threading.Thread(target=handle_client, args=(client_socket,))
        client_thread.start()

面向对象版本(方便代码复用)

import socket
import threading


class HttpWebServer:
    def __init__(self):
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.tcp_server_socket.bind(('', 8080))
        self.tcp_server_socket.listen(128)

    def handle_client(self, client_socket):
        client_request_data = client_socket.recv(1024).decode()
        request_data = client_request_data.split(' ')

        if len(request_data) == 1:
            client_socket.close
            return
        requestspath = request_data[1]
        if requestspath == '/':
            requestspath = '/index.html'
        try:
            with open('.' + requestspath, 'rb') as fp:
                file_data = fp.read()
        except Exception as e:
            response_line = 'HTTP/1.1 404 Not Found \r\n'
            response_header = 'Server:pwb\r\n'
            response_body = "404 Not Found"
            response_data = (response_line + response_header + '\r\n' + response_body).encode()
            client_socket.send(response_data)

        else:
            response_line = 'HTTP/1.1 200 OK \r\n'
            response_header = 'Server:pwb\r\n'
            response_body = file_data
            response_data = (response_line + response_header + '\r\n').encode() + response_body
            client_socket.send(response_data)
        finally:
            client_socket.close()

    def start(self):
        while True:
            client_socket, client_ip = self.tcp_server_socket.accept()
            client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))
            client_thread.start()


if __name__ == '__main__':
    my_web_server = HttpWebServer()
    my_web_server.start()

命令行启动动态绑定端口号(最终版)

在文件中引入sys模块用来获取命令行输入内容,在代码中输出sys.argv即可看到如下结果

 在代码中对获取到的argv[1]即输入的端口号进行验证,然后传入方法中,错误则发出提示,结果如下

python高级学习笔记Day02--python静态Web服务器的搭建_第2张图片

现在就可以在命令行启动服务器并指定端口号了!!!!

 代码如下:

import socket
import threading
import sys


class HttpWebServer:
    def __init__(self, port):
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        self.tcp_server_socket.bind(('', port))
        self.tcp_server_socket.listen(128)

    def handle_client(self, client_socket):
        client_request_data = client_socket.recv(1024).decode()
        request_data = client_request_data.split(' ')

        if len(request_data) == 1:
            client_socket.close
            return
        requestspath = request_data[1]
        if requestspath == '/':
            requestspath = '/index.html'
        try:
            with open('.' + requestspath, 'rb') as fp:
                file_data = fp.read()
        except Exception as e:
            response_line = 'HTTP/1.1 404 Not Found \r\n'
            response_header = 'Server:pwb\r\n'
            response_body = "404 Not Found"
            response_data = (response_line + response_header + '\r\n' + response_body).encode()
            client_socket.send(response_data)

        else:
            response_line = 'HTTP/1.1 200 OK \r\n'
            response_header = 'Server:pwb\r\n'
            response_body = file_data
            response_data = (response_line + response_header + '\r\n').encode() + response_body
            client_socket.send(response_data)
        finally:
            client_socket.close()

    def start(self):
        while True:
            client_socket, client_ip = self.tcp_server_socket.accept()
            client_thread = threading.Thread(target=self.handle_client, args=(client_socket,))
            client_thread.start()


def main():
    print(sys.argv)
    if len(sys.argv) != 2:
        print("Input Error:Should be python3 xxx.py port")
        return
    if not sys.argv[1].isdigit():
        print("Input Error:Should be python3 xxx.py port")
        return
    port = int(sys.argv[1])
    my_web_server = HttpWebServer(port)
    my_web_server.start()


if __name__ == '__main__':
    main()
 

你可能感兴趣的:(Python高级,python,开发语言,后端)