作业 - Python 代理服务器

2024-05-12

对于编程练习(摘自《计算机网络:自上而下的方法》(第 6 版)作者:Kurose 和 Ross),我们正在尝试用 python 开发一个简单的代理服务器。

我们得到了以下代码,无论它在哪里#Fill in start. ... #Fill in end.这就是我们需要编写代码的地方。我的具体问题和尝试将在这个原始片段下方。

我们需要使用以下命令启动 python 服务器:python proxyserver.py [server_ip]然后导航到localhost:8888/google.com当我们完成后它应该可以工作。

from socket import *
import sys
if len(sys.argv) <= 1:
  print 'Usage : "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server'
  sys.exit(2)

# Create a server socket, bind it to a port and start listening 
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
# Fill in end.

while 1:
  # Strat receiving data from the client
  print 'Ready to serve...'
  tcpCliSock, addr = tcpSerSock.accept()
  print 'Received a connection from:', addr 
  message = # Fill in start. # Fill in end. print message

  # Extract the filename from the given message print message.split()[1]
  filename = message.split()[1].partition("/")[2] print filename
  fileExist = "false"
  filetouse = "/" + filename
  print filetouse
  try:
    # Check wether the file exist in the cache
    f = open(filetouse[1:], "r")
    outputdata = f.readlines()
    fileExist = "true"

    # ProxyServer finds a cache hit and generates a response message     
    tcpCliSock.send("HTTP/1.0 200 OK\r\n") 
    tcpCliSock.send("Content-Type:text/html\r\n")
    # Fill in start.
    # Fill in end.
      print 'Read from cache'
  # Error handling for file not found in cache
except IOError:
  if fileExist == "false":
    # Create a socket on the proxyserver
    c = # Fill in start. # Fill in end. 
    hostn = filename.replace("www.","",1)
    print hostn
      try:
        # Connect to the socket to port 80
        # Fill in start.
        # Fill in end.

        # Create a temporary file on this socket and ask port 80 for the file requested by the client
        fileobj = c.makefile('r', 0)
        fileobj.write("GET "+"http://" + filename + "HTTP/1.0\n\n")

        # Read the response into buffer
        # Fill in start.
        # Fill in end.

        # Create a new file in the cache for the requested file. 
        # Also send the response in the buffer to client socket and the corresponding file in the cache
        tmpFile = open("./" + filename,"wb")
        # Fill in start.
        # Fill in end.
      except:
        print "Illegal request"
    else:
      # HTTP response message for file not found 
      # Fill in start.
      # Fill in end.
  # Close the client and the server sockets
    tcpCliSock.close()
# Fill in start.
# Fill in end.

其中说:

# Create a socket on the proxyserver
c = # Fill in start. # Fill in end. 

I tried:

c = socket(AF_INET, SOCK_STREAM)

这似乎是创建套接字的方式,然后为了连接到主机的端口 80,我有:

c.connect((hostn, 80))

Here, hostn是正确的google.com根据我拥有的一些当地打印报表。我要填写的下一部分说#Read response into buffer但我不太明白那是什么意思。我认为这与fileobj这是在上面创建的。

预先感谢,如果我遗漏了任何应该添加的内容,请告诉我。

UPDATE

我当前的代码可以在这里找到,看看我一直在尝试什么:

https://github.com/ardavis/Computer-Networks/blob/master/Lab%203/ProxyServer.py https://github.com/ardavis/Computer-Networks/blob/master/Lab%203/ProxyServer.py


这似乎是我潜在的解决方案。作业中的 pdf 提到我最后需要做一些事情,但不确定它是什么。但缓存和代理似乎与此相关。我希望它对其他人有帮助。

from socket import *
import sys

if len(sys.argv) <= 1:
    print 'Usage: "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address of the Proxy Server'
    sys.exit(2)

# Create a server socket, bind it to a port and start listening
tcpSerPort = 8888
tcpSerSock = socket(AF_INET, SOCK_STREAM)

# Prepare a server socket
tcpSerSock.bind(('', tcpSerPort))
tcpSerSock.listen(5)

while True:
    # Start receiving data from the client
    print 'Ready to serve...'
    tcpCliSock, addr = tcpSerSock.accept()
    print 'Received a connection from: ', addr
    message = tcpCliSock.recv(1024)

    # Extract the filename from the given message
    print message.split()[1]
    filename = message.split()[1].partition("/")[2]
    fileExist = "false"
    filetouse = "/" + filename
    try:
        # Check whether the file exists in the cache
        f = open(filetouse[1:], "r")
        outputdata = f.readlines()
        fileExist = "true"
        print 'File Exists!'

        # ProxyServer finds a cache hit and generates a response message
        tcpCliSock.send("HTTP/1.0 200 OK\r\n")
        tcpCliSock.send("Content-Type:text/html\r\n")

        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            tcpCliSock.send(outputdata[i])
        print 'Read from cache'

        # Error handling for file not found in cache
    except IOError:
        print 'File Exist: ', fileExist
        if fileExist == "false":
            # Create a socket on the proxyserver
            print 'Creating socket on proxyserver'
            c = socket(AF_INET, SOCK_STREAM)

            hostn = filename.replace("www.", "", 1)
            print 'Host Name: ', hostn
            try:
                # Connect to the socket to port 80
                c.connect((hostn, 80))
                print 'Socket connected to port 80 of the host'

                # Create a temporary file on this socket and ask port 80
                # for the file requested by the client 
                fileobj = c.makefile('r', 0)
                fileobj.write("GET " + "http://" + filename + " HTTP/1.0\n\n")

                # Read the response into buffer
                buff = fileobj.readlines() 

                # Create a new file in the cache for the requested file.
                # Also send the response in the buffer to client socket
                # and the corresponding file in the cache
                tmpFile = open("./" + filename, "wb")
                for i in range(0, len(buff)):
                    tmpFile.write(buff[i])
                    tcpCliSock.send(buff[i])

            except:
                print 'Illegal request'

        else:
            # HTTP response message for file not found
            # Do stuff here
            print 'File Not Found...Stupid Andy'
            a = 2
    # Close the socket and the server sockets
    tcpCliSock.close()

# Do stuff here
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

作业 - Python 代理服务器 的相关文章

  • 在二维数组中进行所有可能的组合

    我正在尝试制作具有所有可能组合的 4x4 16 像素黑白图像数组 我制作了以下数组作为模板 template 0 0 0 0 start with all white pixels 0 0 0 0 0 0 0 0 0 0 0 0 然后我想迭
  • 如何打印前面有一定数量空格的整数?

    C has printf Xd Y 它只打印整数 X 并使其在控制台窗口上占据 Y 空格 例如 printf 3d 10 console 10 printf 5d 5 console 5 我如何在 python 3 中使用它 This pr
  • 需要根据数据框中的行号应用不同的公式

    我正在努力在数据框中找到某种移动平均值 该公式将根据正在计算的行数而变化 实际场景是我需要计算Z列 Edit 2 以下是我正在使用的实际数据 Date Open High Low Close 0 01 01 2018 1763 95 176
  • 函数名称未定义

    我有一段代码 看起来像这样 if name main main def main print hello 但是 当我尝试运行此代码时 出现错误 NameError 名称 main 未定义 我是否没有在函数 def main 的第一行定义名称
  • 使用ideone时如何传入命令行参数?

    我正在使用 ideone 在线解释器 http ideone com http ideone com 来测试一些 C 和 Python 程序 如何指定命令行参数而不是使用 STDIN 输入 看起来你不能 但是快速破解应该做的伎俩 stati
  • 是否可以在 IPython 控制台中显示 pandas 样式?

    是否可以显示熊猫风格 https pandas pydata org pandas docs stable user guide style html在 iPython 控制台中 Jupyter 笔记本中的以下代码 import panda
  • DataFrame.loc 的“索引器太多”

    我读了关于切片器的文档 http pandas pydata org pandas docs stable advanced html using slicers一百万次 但我从来没有理解过它 所以我仍在试图弄清楚如何使用loc切片Data
  • lmfit模型拟合然后预测

    我正在领养lmfit进行曲线拟合并使用拟合模型进行预测 然而下面的代码并没有达到我想要的效果 能否请你帮忙 谢谢 import numpy as np from lmfit import Model def linearModel x a0
  • Python 中“is”运算符的语义是什么?

    如何is运算符确定两个对象是否相同 它是如何工作的 我找不到它的记录 来自文档 http docs python org reference datamodel html 每个对象都有一个身份 一个类型 和一个值 对象的身份 一旦发生就永远
  • argparse 不检查位置参数

    我正在创建一个脚本 它使用 argparse 接受位置参数和可选参数 我已经阅读了 Doug 的教程和 python 文档 但找不到答案 parser argparse ArgumentParser description script t
  • 右键单击 QPushButton 上的 contextMenu

    对于我的应用程序 我在 Qt Designer 中创建了一个 GUI 并将其转换为 python 2 6 代码 关于一些QPushButton 与设计器创建 我想添加右键单击上下文菜单 菜单选项取决于应用程序状态 如何实现这样的上下文菜单
  • 如何在 python 中使用交叉验证执行 GridSearchCV

    我正在执行超参数调整RandomForest如下使用GridSearchCV X np array df features all features y np array df gold standard labels x train x
  • 为什么 pip 已经是最新的了却要求我升级?

    我全新安装了 python 3 7 1 64 位 并使用最新的 pyCharm 作为我的 IDE 我在这台机器上没有安装其他 python 我去安装 numpy 并收到以下消息 venv C Users John PycharmProjec
  • 使用 Python-VLC 的 PyInstaller:无属性“media_player_new”错误

    我使用 Python VLC 创建视频播放器 并使用 PyInstaller 在 Windows 10 计算机上生成可执行文件 最初 它给了我错误 Import Error Failed to load dynlib dll libvlc
  • 增强迪基-富勒测试中的 BIC 在 Python 中到底是如何工作的?

    这个问题是关于 statsmodels tsa stattools python 库 adfuller 中的增强迪基 富勒测试实现 原则上 AIC 和 BIC 应该计算一组可用模型的信息标准 并选择最好的模型 信息损失最低的模型 但它们在增
  • 在Python中随机交错2个数组

    假设我有两个数组 a 1 2 3 4 b 5 6 7 8 9 我想将这两个数组交错为变量 c 注意 a 和 b 不一定具有相同的长度 但我不希望它们以确定性的方式交错 简而言之 仅仅压缩这两个数组是不够的 我不想要 c 1 5 2 6 3
  • 解析整数集的字符串并列出间隔

    I have 2 5 7 9 12 string 我想从中获取 2 5 7 8 9 12 列表 python中有没有内置的函数 Thanks UPD 我想 直接的答案是No 不管怎样 谢谢你的 片段 使用一个 建议者斯文 马尔纳克 s 2
  • 为什么我会在 Python 字符串格式中使用除 %r 之外的其他内容?

    我偶尔会使用 Python 字符串格式 这可以像这样完成 print int i Float f String s 54 34 434 some text 但是 这也可以这样做 print int r Float r String r 54
  • python 中的 F 字符串前缀给出语法错误[重复]

    这个问题在这里已经有答案了 我有一个名为 method 的变量 它的值是 POST 但是当我尝试运行时print f method method is used 它不断在最后一个双引号处给出语法错误 我找不到它这样做的原因 我正在使用 py
  • 如何使用 python 模块的多个 git 分支?

    我想使用 git 来同时处理我正在编写的模块中的多个功能 我目前正在使用 SVN 只有一个工作区 因此我的 PYTHONPATH 上只有该工作区 我意识到这不太理想 所以我想知道是否有人可以建议一种更 正确 的方法来做到这一点 让我用一个假

随机推荐

  • CMake - 作为构建过程的一部分运行测试并将标准输出捕获到文件

    我们有几个单元测试 我们希望将其作为构建过程的一部分运行 为了实现这一目标 我有一个帮助程序脚本 它创建一个运行测试的自定义命令 如果成功 则创建一个文件 test name passed 然后我添加一个自定义目标 test name ru
  • Typescript - 联合类型

    我创建了以下界面 export interface Message date Timestamp Date interface Timestamp seconds number nanoseconds number 不知道为什么 我收到以下
  • ManyToOne 关系上的 Hibernate @Where 注释

    我最近开始重构我的项目 因为我必须在一些表中添加额外的列 额外的列是一个枚举 待定或活动 由于这一更改 我现在需要重构所有查询 以便仅在状态为 活动 时检索行 经过一些研究 我发现我们可以使用 Where 注释来注释实体 当我在简单的列上使
  • 为什么 mex 文件中的 OpenMP 仅产生 1 个线程?

    我是 OpenMP 新手 我有以下代码 使用配置了 MSVS2010 的 Matlab mex 可以正常编译 计算机有 8 个可用处理器 我也使用 matlabpool 检查过 include mex h include
  • Webix 树节点的 Font Awesome 图标

    Webix 与 Font Awesome 集成 http docs webix com desktop icon types html 但是如何使用 Font Awesome 图标代替树中的默认文件夹 文件图标来设置各个节点的样式呢 这是我
  • javax.faces.context.FacesContext.isReleased(FacesContext.java:609) 处的 java.lang.UnsupportedOperationException

    我正在集成 SWF 2 2 1 Primefaces 2 2 1 JSF 2 Spring Security 3 Spring 3 1 0M1 我能够访问 Spring web flow xml 中提到的第一页 但出现以下错误 com su
  • 类型错误:“NodeView”对象不支持项目分配 - NetworkX

    我正在完成本教程 https www datacamp com community tutorials networkx python graph tutorial https www datacamp com community tuto
  • python 中的按钮数组

    我想创建一个按钮网格 单击它们时将切换颜色 目前 每个按钮都会触发右下角的按钮 下面是代码 有两个问题 为什么会这样做以及如何纠正 def main self root Tk frame Frame root frame grid row
  • 如何在水晶报表的页眉中添加图表

    我尝试在水晶报表的页眉中添加图表 但它仅在报表页眉和报表页脚中添加 如何在页眉中添加图表 页眉或详细信息部分中不能有图表 图表仅在报告页眉或页脚中起作用 如果页眉中需要图表 请在页眉中创建子报表 并将图表放置在子报表中
  • maven-jar-plugin 不包含 .gitignore 文件

    我尝试使用maven将应用程序打包成jar文件 不知怎的 除了 gitignore文件被添加到 jar 中 为什么会跳过此文件以及如何禁用此文件 即使我尝试像下面这样包含它 包含也会被忽略 并且 jar 文件仍然为空
  • 如何在iOS社交框架中使用SLRequest获取facebook的电子邮件参数

    我尝试使用以下代码来获取登录 iOS 设置 Facebook 的人的电子邮件 请帮助我如何从 SLRequest 获取电子邮件 void getMyDetails if accountStore accountStore ACAccount
  • 如果我用opengl绘图的话SDL Renderer就没用了吗?

    我正在学习 SDL2 但我也在使用使用 OpenGL 调用的 imgui 库 从我在网上各种博客上读到的内容来看 我无法轻松混合 SDL2 渲染器和 opengl 调用 我要么使用其中之一 要么使用另一个 我读过的大多数教程都使用渲染器 所
  • 如何允许点击穿过 div 但仍然对悬停做出反应?

    说我有divA部分重叠的divB 我怎样才能允许点击divA穿过去divB但仍然有hover悬停时触发divA 我知道pointer events none 这使得点击通过 但也阻止了悬停 我也尝试过以下方法 但它不允许点击失败 docum
  • 如何中止 MongoDB shell 中正在运行的查询?

    我不敢相信我必须问这个问题 但是如何停止我刚刚运行的查询 该查询现在正在运行 并且显然需要很长时间才能在 Mongo shell 中完成 Control C似乎会使外壳崩溃 并吐出大量错误 中建议的愚蠢解决方案这个帖子 https stac
  • 在 VS 包项目中获取 dte2 或 TeamFoundationServerExt 对象?

    我正在开发一个 Visual Studio Package 项目 该项目需要连接到我们的 TFS 要读取当前连接 我需要 TeamFoundationServerExt 对象 我应该能够从 dte2 对象中获取该对象 现在我找到了数百个示例
  • swift 中带有字符的单引号

    我已经完成了 C C Java 这些语言告诉我字符用单引号括起来 主要是在遵守正确的语法时 但字符串是双引号的 Swift 的语法是否只允许字符位于单引号内 或者提供这种语法背后有一些有效的原因 逻辑 let char1 Character
  • 交换单链表中的节点

    我正在尝试交换两个节点 例如 如果节点是a and b我正在传递指针 a 1 gt next and b 1 gt next这基本上是节点a and b void swap struct stack a struct stack b str
  • 在 Cocoa/Carbon 下调试 NULL CGContext

    在执行程序期间 我在 XCode 调试控制台中得到以下输出
  • 当传递命名参数时,matplotlib 不会绘图

    有人可以解释这种行为吗 import matplotlib pyplot as plt plt plot x 0 05 0 1 0 15 y 102 211 393 plt show import matplotlib pyplot as
  • 作业 - Python 代理服务器

    对于编程练习 摘自 计算机网络 自上而下的方法 第 6 版 作者 Kurose 和 Ross 我们正在尝试用 python 开发一个简单的代理服务器 我们得到了以下代码 无论它在哪里 Fill in start Fill in end 这就