python3:一个微型的web服务器实现

实验目的:用socket 模拟一个微型的web服务器,当py脚本run起后,实微型web server架起了,然后用本地浏览器访问127.0.0.1:8080(web server的ip_port)时web服务器就会将网页内容传给浏览器,实现网页浏览. 

sw+sys: python3.7.2 + windows10 64bit

本地准备的server端网页为下载的hao123主页(我已上载并上传至这里: 提取码:7fix )

通过这个实验让我学到了:

1. 当get请求一个主页时,要完整的显示一个页面(包括文本、图片、css绚染等)是要get多次请求的

2. respone回复本地页网,open(filepath, rwa)时要特别的注意

import socket
import os

curfilepath = os.path.split(os.path.realpath(__file__))[0].replace("\\" , "/")
print(f'curfilepath: {curfilepath}')


def new_socket_server(new_socket, new_addr):
    if new_addr[0] != '':
        print(f'当前客户端{new_addr}已连接上server端. ')

    # 3.接收信息
    file_name = ''
    request_data = new_socket.recv(1024).decode('utf-8')
    if request_data != '':
        print(f'有收到新的信息,信息如下:\n{request_data}')
        file_name = request_data.splitlines()[0].split(' ')[1]
        print(f'file_name: {file_name}')
        if file_name == '/':
            file_name = '/index.html'
            print(f'file_name: {file_name}')
        with open(curfilepath + '/test.txt', 'a+') as f:
            f.write(file_name + '\n')

    # 4.回复信息
    try:
        f = open(curfilepath + '/htmltest' + file_name, 'rb')
    except:
        response = 'HTTP/1.1 404 NOT FOUND\r\n'
        response += '\r\n'
        response += '----------file not found-------'
        new_socket.send(response.encode('utf-8'))
    else:
        html_content = f.read()
        f.close()
        response = 'HTTP/1.1 200 OK\r\n' + '\r\n'
        new_socket.send(response.encode('utf-8'))
        new_socket.send(html_content)


def main():
    # 1.创建socket
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 2.连接server
    server_ip_port = ('127.0.0.1', 8080)
    tcp_server_socket.bind(server_ip_port)
    tcp_server_socket.listen(128)
    while True:
        print('正在等待client端连接... ...')
        new_socket, new_addr = tcp_server_socket.accept()
        new_socket_server(new_socket, new_addr)
        new_socket.close()


if __name__ == '__main__':
    main()

 

你可能感兴趣的:(python)