python写一个http服务器

import socket
import re


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

    # 2. 绑定地址
    http_server_socket.bind(('', 7890))

    # 3. 监听
    http_server_socket.listen(128)

    while True:
        # 4. 等待客户端连接accept
        new_http_socket, client_address = http_server_socket.accept()

        # 5. 接收浏览器发送过来的请求
        request = new_http_socket.recv(1024)

        # 如果request为空,说明客户端关闭socket
        if request:
            request = str(request, 'utf8')

            # 请求头请求体按行拆分
            request_first_line = request.split('\r\n')[0]

            # 'GET /index.html HTTP/1.1'
            # 从请求头里解析出url地址/index.html
            request_file_name = re.findall(r'/[^ ]*', request_first_line)
            print('接到的请求',request)
            print('寻找请求头里的url',request_file_name)
            request_file_name = request_file_name[0]
            print('客户端请求文件地址:', request_file_name)

            # 如果ip后面没有url
            if request_file_name == '/':
                request_file_name = '/index.html'


            # 在服务器寻找浏览器请求的文件
            # 6. 返回http格式数据

            try:
                f = open('.'+request_file_name,'r')
            except Exception:
                response_header = "HTTP/1.1 404 NOT FOUND\r\n" #\r\n是为了兼容windows的换行
                response_empty_line = "\r\n" #加一个空行
                response_body = 'File not found'
            else:

                response_header = "HTTP/1.1 200 OK\r\n" #\r\n是为了兼容windows的换行
                response_empty_line = "\r\n" #加一个空行
                response_body = f.read()
                f.close()

            # 拼接响应信息:响应头+空行+响应体
            response = ''.join([response_header,response_empty_line,response_body])
            response = bytes(response, 'utf8')

            new_http_socket.send(response)

        # 7. 关闭
        else:
            new_http_socket.close()
            print('服务结束')


if __name__ == "__main__":
    main()

在浏览器输入http://127.0.0.1:7890/index.html即可看到index页面

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值