栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

计算机网络课程实验1——WINDOWS 环境下实现 WEB 服务器(python)

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算机网络课程实验1——WINDOWS 环境下实现 WEB 服务器(python)

代码部分如下:
# coding=utf-8

from http.server import baseHTTPRequestHandler, HTTPServer

PORT_NUMBER = 8080

# This class will handles any incoming request from
# the browser
class myHandler(baseHTTPRequestHandler):
    # Handler for the GET requests
    def do_GET(self):
        if self.path == "/":
            self.path = "./html/from.html"
        if self.path == "/index.html":
            self.path = "./html/to.html"

        try:
            # Check the file extension required and
            # set the right mime type

            sendReply = False
            if self.path.endswith(".html"):
                mimetype = 'text/html'      # mimetype用来指示文件类型的字符串
                sendReply = True
            if self.path.endswith(".jpg"):
                mimetype = 'image/jpg'
                sendReply = True
            if self.path.endswith(".gif"):
                mimetype = 'image/gif'
                sendReply = True
            if self.path.endswith(".js"):
                mimetype = 'application/javascript'
                sendReply = True
            if self.path.endswith(".css"):
                mimetype = 'text/css'
                sendReply = True
            if sendReply:
                # Open the static file requested and send it
                f = open(self.path)
                self.send_response(200)
                self.send_header('Content-type', mimetype)
                self.end_headers()
                self.wfile.write(f.read().encode('utf-8'))
                f.close()
            return

        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)


try:
    # Create a web server and define the handler to manage the
    # incoming request
    server = HTTPServer(('127.0.0.1', PORT_NUMBER), myHandler)
    print('Started httpserver on port ', PORT_NUMBER)

    # Wait forever for incoming http requests
    server.serve_forever()

except KeyboardInterrupt:
    print('^C received, shutting down the web server')
    server.socket.close()
代码分析:

本次实验通过Python程序实现web服务器的功能,其中代码的前半段是对于程序文件目录中的HTML文件进行相对路径到绝对路径的调整和修正,确保程序可以正确的找到我们指定的和HTML文件以及图片等网页资源。
代码的后半段,则是整个程序实现web功能的主要部分,主要为以下几个函数,共同实现get请求的处理。

self.send_response(200)
self.send_header('Content-type', mimetype)
self.end_headers()
self.wfile.write(f.read().encode('utf-8'))

代码实现效果:运行Python程序后进入localhost8080出现一下界面:

点击next_page之后,出现另一个界面:

实验心得与体会

通过这次实验,我对html协议有了更深刻的了解。知道了怎么用Python搭建一个web服务器。并进行简单的网页跳转和8080页面编写。对于HTTP 协议下客户/服务器模式中信息交换的实现原理、流程(建立连接、发送请求、发送响应、关闭连接),相比于理论知识,在动手实践后能更好地掌握和理解。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/725288.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号