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>
~         
相关推荐
vx_BS8133020 分钟前
【直接可用源码免费送】计算机毕业设计精选项目03574基于Python的网上商城管理系统设计与实现:Java/PHP/Python/C#小程序、单片机、成品+文档源码支持定制
java·python·课程设计
gzxx2007sddx27 分钟前
windows vnpy运行过程及问题记录
python·量化·vnpy
星火开发设计34 分钟前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
Gorgous—l1 小时前
数据结构算法学习:LeetCode热题100-多维动态规划篇(不同路径、最小路径和、最长回文子串、最长公共子序列、编辑距离)
数据结构·学习·算法
230万光年的思念1 小时前
【无标题】
python
shengli7221 小时前
机器学习与人工智能
jvm·数据库·python
2301_765703141 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
Hello_Embed2 小时前
libmodbus 移植 STM32(基础篇)
笔记·stm32·单片机·学习·modbus
追风少年ii2 小时前
多组学扩展---分子对接pyrosetta
python·数据分析·空间·单细胞