Python学习-实现简单的http服务

基于Python实现一个简单的HttpServer,当用户在浏览器中输入IP地址:8000时,则会返回index.html页面内容,访问其它信息,则会返回错误信息(404)

py 复制代码
"""
httpserver v1.0
1.获取来自浏览器的请求,
2.判断如果请求内容是 / ,就将index.html返回给客户端
3.如果请求是其它内容则返回404
"""
from socket import *

# 客户端处理

def request(connfd):
    # 获取请求,提取请求内容
    data = connfd.recv(4096)
    # 防止浏览器异常退出
    if not data:
        return

    content = data.decode()
    listcon = content.split("\r\n")
    reqinfo = listcon[0].split(" ")[1]
    print(reqinfo)
    # 判断是 / 返回index.html,不是则返回404
    if reqinfo == "/":
        with open("index.html") as f:
            response = "HTTP/1.1 200 OK\r\n"
            response += "Content-Type:text/html\r\n"
            response += "\r\n"
            response += f.read()
            print(response)
    else:
        response = "HTTP/1.1 404 Not Found\r\n"
        response += "Content-Type:text/html\r\n"
        response += "\r\n"
        response += "<h1>Sorry .....</.h1>\r\n"
    connfd.send(response.encode())

sockfd = socket()
sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
sockfd.bind(('0.0.0.0', 8000))
sockfd.listen(3)

while True:
    connfd, addr = sockfd.accept()
    request(connfd)  # 处理客户端请求
html 复制代码
<!--index.html内容 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>人生在世,好好努力</title>
</head>
<body>
好好努力吧,少年
</body>
</html>
~         
相关推荐
2401_834517077 分钟前
AD学习笔记-35 多层线路和装配图的导出
笔记·学习
smile_Iris14 分钟前
Day 38 GPU训练及类的call方法
开发语言·python
嗷嗷哦润橘_22 分钟前
AI Agent学习:MetaGPT项目之RAG
人工智能·python·学习·算法·deepseek
Smart-Space30 分钟前
tkinter绘制组件(47)——导航边栏
python·tkinter·tinui
Radan小哥40 分钟前
Docker学习笔记—day012
笔记·学习·docker
ULTRA??1 小时前
KD-Tree的查询原理
python·算法
电饭叔1 小时前
TypeError:unsupported operand type(s) for -: ‘method‘ and ‘int‘
开发语言·笔记·python
老歌老听老掉牙1 小时前
使用贝叶斯因子量化假设验证所需数据量
python·贝叶斯因子·假设
nix.gnehc1 小时前
poetry 常用命令
python·poetry
一人の梅雨2 小时前
淘宝商品视频接口深度解析:从视频加密解密到多端视频流重构
java·开发语言·python