簡體   English   中英

家庭作業 - Python 代理服務器

[英]Homework - Python Proxy Server

對於編程練習(來自 Kurose 和 Ross 的計算機網絡:自上而下的方法(第 6 版) ),我們正在嘗試用 Python 開發一個簡單的代理服務器。

我們得到了以下代碼,無論它在哪里寫着#Fill in start. ... #Fill in end. #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. 

我試過:

c = socket(AF_INET, SOCK_STREAM)

這似乎是您創建套接字的方式,然后為了連接到主機的端口 80,我有:

c.connect((hostn, 80))

在這里,根據我的一些本地打印語句, hostn是正確的google.com 我要填寫的下一部分說#Read response into buffer但我真的不明白那是什么意思。 我認為它與上面創建的fileobj有關。

在此先感謝,如果我遺漏了任何我應該添加的內容,請告訴我。

更新

可以在此處找到我當前的代碼以查看我一直在嘗試的內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM