Python代理服务器无法连接到主机

时间:2017-04-21 18:48:48

标签: python sockets proxy-server

我正在为学校作业制作一个python代理服务器,我已经得到了以下代码。当我在命令提示符下运行它并尝试连接到谷歌时,代码不会超过连接服务器套接字,但页面仍然连接。老实说,我不知道为什么它甚至没有通过连接步骤。想法?

编辑:是的还有关于此的其他家庭作业帖子,但是它们似乎都没有解决第8行的sys.exit()结束脚本(据我所知)并且每当我们发表评论时,脚本仍然没有超过连接服务器套接字并命中“非法请求”异常。

from socket import *
from urllib2 import HTTPError #Used for 404 Not Found error
import sys
import requests

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)

#POST request extension
print 'Fetching webpage using POST'
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
print 'Printing webpage body'
print r.text

print 'Creating and binding socket for proxy server'
# Create a server socket, bind it to a port and start listening
tcpServerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
tcpServerSock.bind(('',8888))
tcpServerSock.listen(10) #the number is the maximum number of connections     we want to have
# Fill in end.

while 1:
    # Start receiving data from the client
    print 'Ready to serve...'
    tcpClientSock, addr = tcpServerSock.accept()
    print 'Received a connection from:', addr
    # Fill in start. 
    message = tcpClientSock.recv(4096) #receive data with buffer size      4096
    # Fill in end.

    print 'Printing message'
    print message
    # Extract the filename from the given message
    print message.split()[1]
    filename = message.split()[1].partition("/")[2]
    print '\n'
    print 'Printing file name'
    print filename
    fileExist = "false"
    filetouse = "/" + filename
    print '\n'
    print 'Printing file to use'
    print filetouse
    print '\n'
    try:
        # Check whether 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
        tcpClientSock.send("HTTP/1.0 200 OK\r\n")
        tcpClientSock.send("Content-Type:text/html\r\n")
        # Fill in start.
        for x in range(0,len(outputdata)):
            tcpClientSock.send(outputdata[x])
        # Fill in end.

        print 'Read from cache\n'
    # Error handling for file not found in cache
    except IOError:
        if fileExist == "false":
            # Create a socket on the proxyserver
            # Fill in start. 
            print 'Creating server socket\n'
            c = socket(AF_INET, SOCK_STREAM)
            # Fill in end.

            hostn = filename
            #hostn = filename.replace("www.","",1)
            print 'Printing host to connect'
            print hostn
            print '\n'
            print 'Attempting to connect to hostn\n'
            try:
                # Connect to the socket to port 80
                # Fill in start.
                c.connect((hostn,80)) #port 80 is used for http web pages
                # 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")

                # Show what request was made
                print "GET "+"http://" + filename + " HTTP/1.0"

                # Read the response into buffer
                # Fill in start.
                buff = fileobj.readlines() #reads until EOF and returns a     list with the lines read
                # 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") #creates the temp      file for the requested file
                # Fill in start.
                for x in range(0, len(buff)):
                    tmpFile.write(buff[x]) #writes the buffer response    into the temp file (cache?)
                    tcpClientSock.send(buff[x]) #sends the response saved     in the buffer to the client
                # Fill in end.
                tmpFile.close()

            except:
                print "Illegal request\n"
        else:
            # HTTP response message for file not found
            # Fill in start.
            print 'File not found'
            # Fill in end.
    #404 not found error handling
    except HTTPError as e:
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code

    # Close the client and the server sockets
    tcpClientSock.close()
# Fill in start.
tcpServerSock.close()
# Fill in end

1 个答案:

答案 0 :(得分:0)

我知道这个问题很旧,Jose M的任务可能已经过期了。

if len(sys.argv) <= 1:检查是否需要传递另一个参数,即服务器的IP。注释掉出口实际上可以消除错误检查。

上面代码的解决方法是将第20行从此tcpSerSock.bind(('', 8888))更改为tcpSerSock.bind((sys.argv[1], tcpSerPort))

然后必须正确python ProxyServer.py 127.0.0.1调用脚本。