首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python代理服务器无法连接到主机

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

Stack Overflow用户
提问于 2017-04-22 02:48:48
回答 1查看 1.4K关注 0票数 0

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

编辑:还有其他关于这方面的作业帖子,但似乎没有一个涉及到第8行的sys.exit()结束脚本的事实(据我所知),每当我们注释掉它时,脚本仍然无法连接服务器套接字,并命中“非法请求”异常。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2018-07-13 07:35:23

我知道这个问题很老了,而且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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43549971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档