2016-05-28 13 views
0
from socket import * 
import sys 

# Create a server socket, bind it to a port and start listening 
tcpSerSock = socket(AF_INET, SOCK_STREAM) 
serverPort = 12000 
tcpSerSock.bind(('', serverPort)) 
tcpSerSock.listen(1) 
print ("Server ready") 

while 1==1: 
    # Start receiving data from the client. e.g. request = "GET http://localhost:portNum/www.google.com" 
    tcpCliSock, addr = tcpSerSock.accept() 
    print ('Received a connection from:', addr) 
    request = str(tcpCliSock.recv(1024).decode()) 
    print ("Requested " + request) 
    # Extract the file name from the given request 
    fileName = request.split()[1] 
    print ("File name is " + fileName) 

    fileExist = "false" 
    fileToUse = "/" + fileName 

    print ("File to use: " + fileToUse) 
    try: 
    # Check wether the file exist in the cache. The open will fail and go to "except" in case the file doesn't exist. Similar to try/catch in java 
    f = open(fileToUse[1:], "r")      
    outputData = f.readlines()       
    fileExist = "true" 
    # ProxyServer finds a cache hit and generates a response message 
    tcpCliSock.send("HTTP/1.1 200 OK\r\n")    
    tcpCliSock.send("Content-Type:text/html\r\n") 
    tcpCliSock.send(outputData) 
    print ('This was read from cache')  

    except IOError: 
    if fileExist == "false": 
     # Create a socket on the proxyserver 
     c = socket(AF_INET, SOCK_STREAM) 
     hostn = fileName.replace("www.","",1) #max arg specified to 1 in case the webpage contains "www." other than the usual one   
     print (hostn)         
     try: 
      # Connect to the socket to port 80 
      c.bind(('', 80)) 
      # Create a temporary file on this socket and ask port 80 for the file requested by the client 
      print("premake") 

      fileObj = c.makefile('r', 0) 

      print("postmake") 
      fileObj.write("GET " + "http://" + fileName + " HTTP/1.1\r\n") 
      # Read the response into buffer 
      print("post write") 
      buff = fileObj.readlines() 
      # Create a new file in the cache for the requested file. 
      tmpFile = open("./" + filename,"wb") 
      # Send the response in the buffer to both client socket and the corresponding file in the cache 
      for line in buff: 
       tmpFile.write(line) 
      tcpCliSock.send(tmpFile) 

     except: 
      print ("Illegal request") 
      break            
    else: 
     # HTTP response message for file not found 
     print("HTTP response Not found") 

# Close the client and the server sockets  
tcpCliSock.close() 
#tcpSerSock.close() 

「IOErrorを除いて」入力された「try」を実行することは決してありません。問題はpython 3のための貧弱なドキュメントを持っているsocket.makefile(mode、buffsize)関数のようです。私は 'rwb'、 'r +'、 'r + b'などを関数に渡してみましたが、私はファイルを作成し、それ以降は書き込めません。HTTPプロキシを作成中にpython 3でsocket.makefileが発生する

答えて

0

これはpython2.7とpython3の問題です。 makefile('r',0)はpython 2.7で動作しますが、python3ではmakefile('r',None)が必要です。 python2.7のドキュメントから

socket.makefile([mode[, bufsize]])

のpython3のドキュメントから: socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

+0

ものpython3支持体には、内部バッファファイルを処理するソケットプログラミングのための()およびRECV()関数を送信します。したがって、あなたはまた、FileObjを完全に取り除くことができます。 (これをもう一度チェックしてください) – bhakku

+0

ありがとう! pythonはソケット/ネットワークプログラミングのための特に良い環境を提供していないようです:) –

関連する問題