返回用户指定页面的web服务器

简介: import socketimport reimport osdef handle_client(socket_con): """ 接收来自客户端的请求,并接收请求报文,解析,返回 """ # 1、服务器接收客户端的请求报文 request = socket_con.
import socket
import re
import os

def handle_client(socket_con):
    """
     接收来自客户端的请求,并接收请求报文,解析,返回
    """
    # 1、服务器接收客户端的请求报文
    request = socket_con.recv(4096).decode()
    # 以行切割请求报文为列表
    res = request.split('\r\n')
    # 取第一位(请求行):GET / HTTP/1.1,并用正则切割GET / HTTP/1.1,取出路径位置
    path = re.match('\w+\s(\S+)',res[0])
    path = path.group(1)
    # 判断路径长度,大于一则拼接出路径,小于等于一则显示首页
    if len(path) > 1:
        # 路径取出,开始拼接资源路径(绝对路径自己填写)
        path = '# 文件夹绝对路径' + path
        print(path)
    else:
        # 显示首页代码
        response_line = 'HTTP/1.1 200 OK\r\n'
        response_head = 'Content-Type:text/html;charset=utf-8\r\n'
        response_body = '''
            <html>
            <head>
            <title>首页</title>
            <style>
            body {
                    width: 35em;
                    margin: 0 auto;
                    font-family: Tahoma, Verdana, Arial, sans-serif;
                 }
            </style>
            </head>
            <body>
            <h1>首页</h1>
            <p>欢迎来到首页</p>
            <p><em>感谢你的使用</em></p>
            </body>
            </html>'''
        response = response_line + response_head + '\r\n' + response_body
        socket_con.send(response.encode())
        socket_con.close()
    # 路径大于一并取出之后判断资源是否存在
    if not os.path.exists(path):
        # 资源不存在则显示资源不存在界面
        response_line = 'HTTP/1.1 404 NOT FOUND\r\n'
        response_head = 'Content-Type:text/html;charset=utf-8\r\n'
        response_body = '''
            <html>
            <head>
            <title>错误</title>
            <style>
                body {
                    width: 35em;
                    margin: 0 auto;
                    font-family: Tahoma, Verdana, Arial, sans-serif;
                }
            </style>
            </head>
            <body>
            <h1>你请求的资源不存在!</h1>
            <p>如果你想访问一个资源,请输入正确的资源路径</p>
            <p><em>感谢你的使用</em></p>
            </body>
            </html>'''
        response = response_line + response_head + '\r\n' + response_body
        socket_con.send(response.encode())
        socket_con.close()
        return
    else:
        # 资源存在以后判断是否是文件,是文件则直接读取
        if os.path.isfile(path):
            response_line = 'HTTP/1.1 200 OK\r\n'
            response_head = 'Server:skylark 2.0\r\n'
            response_head += 'Content-Type:*/*;charset:utf-8\r\n'
            f = open(path, 'rb')
            response_body = f.read()
            response = response_line.encode() + response_head.encode() + '\r\n'.encode() + response_body
            socket_con.send(response)
            socket_con.close()
            return
        else:
            if path.endswith('/'):
                 # 如果是文件夹
                 # 判断文件夹下是否有默认文件,如果有则返回,如果没有则判断服务器是否开启了目录浏览
                 # 默认文件:index.html  default.html
                 # 是否可以访问默认文件开关,True 开 ,False 关
                 default_document = False
                 if default_document:
                     # 判断用户访问的文件夹下是否有index.html 或者 default.html
                     if os.path.exists(path + 'index.html'):
                         response_line = 'HTTP/1.1 200 OK\r\n'
                         response_head = 'Server:skylark 2.0\r\n'
                         response_head += 'Content-Type:*/*;charset:utf-8\r\n'
                         f = open(path + 'index.html', 'rb')
                         response_body = f.read()
                         response = response_line.encode() + response_head.encode() + '\r\n'.encode() + response_body
                         socket_con.send(response)
                         socket_con.close()
                         return
                     elif os.path.exists(path + 'default.html'):
                         response_line = 'HTTP/1.1 200 OK\r\n'
                         response_head = 'Server:skylark 2.0\r\n'
                         response_head += 'Content-Type:*/*;charset:utf-8\r\n'
                         f = open(path + 'default.html', 'rb')
                         response_body = f.read()
                         response = response_line.encode() + response_head.encode() + '\r\n'.encode() + response_body
                         socket_con.send(response)
                         socket_con.close()
                         return
                     else:
                         # 如果没有上述两个页面,则可以返回404错误,或者302重定向
                         response_line = "HTTP/1.1 404 Not Found\r\n"
                         response_head = "Server:skylark 2.0\r\n"
                         response_body = "index.html or default.html is not exist!!!"
                         response = response_line + response_head + "\r\n" + response_body
                         socket_con.send(response.encode())
                         socket_con.close()
                # 不能访问默认文件情况下,判断服务器是否开启了目录浏览
                 else:
                     dir_browsing = True
                     if dir_browsing:
                         # 把用户请求的文件夹中所有的文件和文件夹以目录的形式返回到页面中
                         # 获取用户请求的文件夹
                         list_names = os.listdir(path)
                         response_line = 'HTTP/1.1 200 OK\r\n'
                         response_head = 'Server:skylark 2.0\r\n'
                         # 动态的拼接页面,将目录中的文件或者文件夹的名称以HTML页面的方式返回给浏览器
                         response_body = '<html><head><body><ul>'
                         for item in list_names:
                             response_body += "<li><a href = '#'>" + item + "</a></li>"
                         response_body += '</ul></body></head></html>'
                         response = response_line + response_head + "\r\n" + response_body
                         socket_con.send(response.encode())
                         socket_con.close()
                         return
            else:
                # 用户请求的路径没有斜线
                # 重定向到+斜线的目录下,并显示重定向以后的路径(此处可以增加有斜线目录处理方式也就是上面的方法)
                response_line = 'HTTP/1.1 302 Found\r\n'
                response_head = 'Server:skylark 2.0\r\n'
                response_head += 'Content-Type:text/html;charset=utf-8\r\n'
                response_body = '重定向' + path + '/'
                response = response_line + response_head + '\r\n' + response_body
                socket_con.send(response.encode())
                socket_con.close()


def main():
    # 1、服务器创建负责监听的socket
    socket_watch = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    # 2、设置地址重用
    socket_watch.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # 3、绑定监听的端口
    socket_watch.bind(("",8888))
    # 4、设置监听队列
    socket_watch.listen(128)
    # 5、通过循环,不停的接收来自客户端的连接请求
    while True:
        socket_con,con_adds = socket_watch.accept()
        # 注意将con_adds转成字符串
        print("客户端:%s连接成功!!!" % str(con_adds))
        # 接收来自客户端的请求,并接收请求报文,解析,返回
        handle_client(socket_con)

if __name__ == '__main__':
    main()

  

                                                                   -------  知识无价,汗水有情,如需搬运请注明出处,谢谢!

目录
相关文章
|
1月前
|
前端开发
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
43 1
【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
|
6月前
|
UED
判断iframe链接页面 服务器状态
判断iframe链接页面 服务器状态
151 58
|
4月前
|
XML 前端开发 JavaScript
PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑
本文深入探讨了PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑;Ajax则通过异步请求实现页面无刷新更新。文中详细介绍了两者的工作原理、数据传输格式选择、具体实现方法及实际应用案例,如实时数据更新、表单验证与提交、动态加载内容等。同时,针对跨域问题、数据安全与性能优化提出了建议。总结指出,PHP与Ajax的结合能显著提升Web应用的效率和用户体验。
99 3
|
5月前
|
UED
判断iframe链接页面 服务器状态
【10月更文挑战第6天】
50 1
|
5月前
|
编解码 前端开发 JavaScript
使用 CSS 打印样式为 Web 页面设置专业的打印机效果
使用 CSS 打印样式为 Web 页面设置专业的打印机效果
123 2
|
5月前
|
Java PHP
PHP作为广受青睐的服务器端脚本语言,在Web开发中占据重要地位。理解其垃圾回收机制有助于开发高效稳定的PHP应用。
【10月更文挑战第1天】PHP作为广受青睐的服务器端脚本语言,在Web开发中占据重要地位。其垃圾回收机制包括引用计数与循环垃圾回收,对提升应用性能和稳定性至关重要。本文通过具体案例分析,详细探讨PHP垃圾回收机制的工作原理,特别是如何解决循环引用问题。在PHP 8中,垃圾回收机制得到进一步优化,提高了效率和准确性。理解这些机制有助于开发高效稳定的PHP应用。
72 3
html,web页面朗读文字,朗读中文,朗读英文
html,web页面朗读文字,朗读中文,朗读英文
|
6月前
|
数据处理 Python
Django视图:构建动态Web页面的核心技术
Django视图:构建动态Web页面的核心技术
|
4天前
|
弹性计算 运维 监控
【阿里云】控制台使用指南:从创建ECS到系统诊断测评
本文介绍了如何通过阿里云获取ECS云服务器并进行操作系统配置与组件安装,以实现高效的资源管理和系统监控。阿里云凭借强大的基础设施和丰富的服务成为用户首选。文中详细描述了获取ECS、RAM授权、开通操作系统控制台及组件安装的步骤,并展示了如何利用控制台实时监控性能指标、诊断系统问题及优化性能。特别针对idle进程进行了深入分析,提出了优化建议。最后,建议定期进行系统健康检查,并希望阿里云能推出更友好的低成本套餐,满足学生等群体的需求。
58 17
【阿里云】控制台使用指南:从创建ECS到系统诊断测评
|
5天前
|
弹性计算 Linux 数据安全/隐私保护
阿里云幻兽帕鲁联机服务器搭建全攻略,速来抄作业!2025新版教程
阿里云提供2025年最新幻兽帕鲁服务器申请购买及一键开服教程。4核16G配置支持8人,70元/月;8核32G配置支持20人,160元/月。选择配置、地域、操作系统后,点击【一键购买及部署】,约3分钟完成创建。本地安装STEAM客户端并登录,进入游戏选择多人模式,输入服务器IP和端口(8211),即可开始游戏。详细教程及更多问题解答请参考阿里云幻兽帕鲁游戏专区。
49 20

热门文章

最新文章