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

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

"""
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)  # 处理客户端请求
<!--index.html内容 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>人生在世,好好努力</title>
</head>
<body>
好好努力吧,少年
</body>
</html>
~         
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值