web服务器默认返回首页版

当打开一个浏览器之后,服务器肯定会默认打开首页,因此设计为首页模式

import socket

import re

def work(request):
    '''从浏览器请求里解析出资源路径'''
    #获取请求行
    head_list = re.split(r'\r\n',request)
    request_line = head_list[0]


    #获取到请求的资源路径
    data = re.split(r' ',request_line)
    return data[1]


    #对路径的安全检查
    path = data[1]
    if path == '/':
        path = '/index.html'


    return path


def handle_client(client_soc):
    '''获取一个客户端请求'''
    #获取请求头
    client_msg = client_soc.recv(1024*4)
    print(client_msg)
    
    if not client_msg:
        print('客户端已经关闭链接')
        client_soc.close()
        return


    #获取用户请求的资源路径
    path = work(client_msg.decode('utf-8'))#创建了一个寻求资源路径的对象


    try:
        #读取文件内容
        with open('html/html'+ path,'rb') as file:
            file_content = file.read()


        #返回响应数据
        response_line = 'HTTP/1.1 200 OK\r\n'
        response_head = 'server:itcast server 1.0\r\n'
        response = response_line + response_head + '\r\n'
        # client_soc.send(response.encode())
        response_body = file_content
        # client_soc.send(response_body)
    except:
        #读取404文件内容
        with open('html/404.html','rb') as file:
            file_content = file.read()


        #处理响应数据
        response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
        response_head = 'server:itcast server 1.0\r\n'
        response = response_line + response_head + '\r\n'
        # client_soc.send(response.encode())


        response_body = file_content


    client_soc.send(response.encode())
    client_soc.send(response_body)
    #关闭客户端套接字
    client_soc.close()
def main():
    '''创建一个能响应浏览器请求的web服务器'''
    #初始化服务器套接字
    server_soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server_soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # 设置套接字复用地址
    server_soc.bind(('',1419))
    server_soc.listen(128)


    while True:
        #获取客户端链接
        print('正在准备客户端链接...')
        client_soc,client_addr = server_soc.accept()


        #为一个客户端提供服务
        handle_client(client_soc)


    #关闭服务器套接字
    server_soc.close()


if __name__ == '__main__':

    main()


猜你喜欢

转载自blog.csdn.net/wpb74521wrf/article/details/80415446
今日推荐