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>
~         
相关推荐
MrSYJ6 分钟前
pyenv管理多个版本的python,你造吗?我才造
python·llm·ai编程
咕白m6258 分钟前
Python 实现 Word 到 Markdown 的转换
后端·python
β添砖java15 分钟前
python第一阶段第八章文件操作
开发语言·python
天才测试猿16 分钟前
树控件、下拉框、文本框常用测试用例
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
灵梦归希16 分钟前
bugku的奇怪的二维码
python
可可苏饼干18 分钟前
NoSQL 与 Redis
数据库·redis·笔记·学习·nosql
重生之我在番茄自学网安拯救世界29 分钟前
网络安全中级阶段学习笔记(一):DVWA靶场安装配置教程与网络空间搜索语法
笔记·学习·网络安全·靶场·dvwa·fofa·google hack
源代码•宸36 分钟前
GoLang并发简单例子(goroutine + channel + WaitGroup)
开发语言·经验分享·后端·学习·golang