利用python搭建简单http服务器实例

import socket
import re

def http_client(new_socket):
    recv_data = new_socket.recv(1024).decode("utf-8")
    print(recv_data)
    recv_data_list = recv_data.splitlines()
    print(recv_data_list)
    # 使用正则匹配出文件名字
    file_name = ""
    ret = re.match(r"[^/]+(/[^ ]*)", recv_data_list[0])
    if ret:
        file_name = ret.group(1)
        print(file_name)
        if file_name == "/":
            file_name = "/index.html"
            print(file_name)
    send_data_header = "HTTP/1.1 200 OK\r\n"
    send_data_header += "\r\n"
    # 没有访问的文件怎么办
    try:
        f = open("./html" + file_name, "rb")

    except:
        send_data_header = "HTTP/1.1 404 NOT FOUND\r\n"
        send_data_header += "\r\n"
        send_data_header += "

Sorry,not found....

" new_socket.send(send_data_header.encode("utf-8")) else: http_count = f.read() # 发送内容给客服端 new_socket.send(send_data_header.encode("utf-8")) new_socket.send(http_count) new_socket.close() def main(): # 创建套接字 tcp_sever_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_sever_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 绑定端口 tcp_sever_socket.bind(("192.168.13.56", 7890)) # 变为监听 tcp_sever_socket.listen(128) # 处理数据 while True: new_socket, client_addr = tcp_sever_socket.accept() http_client(new_socket) # 关闭套接字 tcp_sever_socket.close() if __name__ == "__main__": main()

一个用python完成的简单http服务器。


你可能感兴趣的:(python_http)