作业-Python代理服务器 [英] Homework - Python Proxy Server

查看:135
本文介绍了作业-Python代理服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For a programming exercise (from Computer Networking: A Top-Down Approach (6th Edition) by Kurose and Ross), we're trying to develop a simple proxy server in python.

我们得到了下面的代码,无论它说什么#Fill in start. ... #Fill in end.,这就是我们需要编写代码的地方.我的具体问题和尝试将在此原始代码段下方.

We were given the following code, wherever it says #Fill in start. ... #Fill in end. that is where we need to write code. My specific question and attempts will be below this original snippet.

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

We need to start the python server with: python proxyserver.py [server_ip] then navigate to localhost:8888/google.com and it should work when we're finished.

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. 

我尝试过:

c = socket(AF_INET, SOCK_STREAM)

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

This seems to be how you create a socket, then for connecting to port 80 of the host, I have:

c.connect((hostn, 80))

在这里,根据我的一些本地打印语句,hostn是正确的google.com.我要填写的下一部分对#Read response into buffer说,但是我真的不明白这是什么意思.我认为它与上面创建的fileobj有关.

Here, hostn is correctly google.com according to some local print statements I have. The next section for me to fill in says to #Read response into buffer but I don't really understand what that means. I presume it has something to do with the fileobj that is created just above.

在此先感谢您是否错过了我应该添加的内容.

Thanks in advance, please let me know if I missed anything I should be adding.

更新

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

My current code can be found here to see what I've been trying:

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

推荐答案

这似乎是我潜在的解决方案.作业中的pdf文件提到我需要在最后做一些事情,不确定是什么.但是高速缓存和代理似乎与此一起起作用.我希望它可以帮助其他人.

This seems to be my potential solution. The pdf from the homework mentions I need to do something at the end, not sure what it is. But the cache and proxy seems to function with this. I hope it helps someone else.

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

这篇关于作业-Python代理服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆