2015-04-05 72 views
0

我创建了一个接收请求的代理服务器,在其缓存中搜索请求的文件。如果可用,则返回缓存的文件。如果文件不可用,那么它会询问实际的服务器,获取它,将其存储在缓存中并将文件返回给客户端。针对网络服务器的Python套接字编程

以下是代码:

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) 
tcpSerSock.bind((sys.argv[1], 8888)) 
tcpSerSock.listen(100) 

while 1: 
    # Strat receiving data from the client 
    print 'Ready to serve...' 
    tcpCliSock, addr = tcpSerSock.accept() 
    print 'Received a connection from:', addr 
    message = tcpCliSock.recv(1024) 
    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") 
     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: 
     if fileExist == "false": 
      # Create a socket on the proxyserver 
      c = socket(AF_INET, SOCK_STREAM)    
      hostn = filename.replace("www.","",1)   
      print hostn         
      try: 
       # Connect to the socket to port 80 
       c.connect((hostn, 80)) 
       # 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 line in buff:              
        tmpFile.write(line);            
        tcpCliSock.send(line); 
      except: 
       print "Illegal request"            
     else: 
      # HTTP response message for file not found 
      tcpCliSock.send("HTTP/1.0 404 sendErrorErrorError\r\n")        
      tcpCliSock.send("Content-Type:text/html\r\n") 
      tcpCliSock.send("\r\n") 
    # Close the client and the server sockets  
    tcpCliSock.close() 
    tcpSerSock.close() 

但对于每一个文件我请求我只得到一个“非法请求”消息打印。似乎有一个问题,代理服务器实际上无法检索客户端请求的文件。有人可以告诉我在哪里可以改进代码。 这是我第一次用Python编码,所以请提及任何小错误。

+2

我投票结束这个问题作为题外话题,因为它是关于调试一段特定的代码。我相信这将是在http://codereview.stackexchange.com/ – 2015-04-05 03:35:18

+1

根据主题,根据代码审查帮助中心,该网站是“关于特定的**工作**代码块的反馈”(强调他们的)并且明确地不是用于“解决问题,调试或理解代码片段”。我相信StackOverflow是这个网站的正确站点(因为它似乎是一个合法的问题,而不是“给我这个codez”),假设OP主要对解决这个“非法请求”错误感兴趣。 – Ixrec 2015-04-05 08:10:27

回答

0

您的请求是非法的。对于普通的http服务器,GET不能包含URL,但只能包含路径。代理的其余部分也包含很多错误。你可能想在你使用send的地方使用sendall。 recv可以少收到一条消息,所以你也必须处理这种情况。 为什么你使用字符串“true”和“false”而不是True和False? 存在安全漏洞,因为您可以通过代理读取计算机上的任何文件。读取二进制文件将不起作用。您不关闭打开的文件。