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>
~         
相关推荐
Freya冉冉9 分钟前
【PYTHON学习】推断聚类后簇的类型DAY18
python·学习·聚类
成子不是橙子29 分钟前
Langchain | Ollama | Python快速上手使用LLM的DEMO
开发语言·python·langchain·ollama
虎头金猫1 小时前
我的远程开发革命:从环境配置噩梦到一键共享的蜕变
网络·python·网络协议·tcp/ip·beautifulsoup·负载均衡·pandas
壹号用户1 小时前
python学习之可迭代对象&迭代器对象
python·学习
蒋星熠1 小时前
基于深度学习的卫星图像分类(Kaggle比赛实战)
人工智能·python·深度学习·机器学习·分类·数据挖掘
虚行1 小时前
Python学习入门
开发语言·python·学习
总有刁民想爱朕ha1 小时前
Python自动化从入门到实战(23):Python打地鼠游戏开发
开发语言·python·游戏开发
科学创新前沿2 小时前
机器学习催化剂设计专题学习
python·学习·机器学习·催化剂·催化剂设计
WIN赢3 小时前
【数据结构与算法_学习精华】
学习
C嘎嘎嵌入式开发4 小时前
(六)机器学习之图卷积网络
人工智能·python·机器学习