gpt4 book ai didi

python - HTTP 代理服务器 python [客户端帮助]

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:29:07 37 4
gpt4 key购买 nike

我认为实现这个代理服务器会很酷。目前对套接字编程还很陌生,但是您将如何制作一个客户端程序,该程序将与代理交互并通过代理将 HTTP GET 请求发送到多个 Web 服务器(例如:reddit.com、google.com、yahoo.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)
tcpSerPort = 8888
tcpSerSock.bind(("", tcpSerPort))
tcpSerSock.listen(5)

while 1:
#start recieving data from the client
print 'Ready to serve...'
tcpCliSock, addr = tcpSerSock.accept()
print 'Recieved a connection from:', addr
message = tcpCliSock.recv(1024)
print message

#extract the filename from a 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 exists in the cache
f = open(filetouse[1:], "r")
outputdata = f.readlines()
fileExist = "true"
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 handeling for file not in cache

except IOError:
if fileExist == "false":
#creates 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)
#creates 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
#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
print "404 Error file not found"
#close the client and the server sockets
tcpCliSock.close()

if __name__ == '__main__':
main()

使用 OS X 10.10.3 和 Python 3.4

还有代码截图的链接: https://smartedblog.files.wordpress.com/2013/05/pr4-1.png (第1部分) https://smartedblog.files.wordpress.com/2013/05/pr4-2.png (第 2 部分)

最佳答案

您有一个永不中断的 while 循环。

while 1:
print 'Ready to serve...'

您的代理输出是什么?看起来它应该无限地打印那一行。您的代理永远不会到达此行 tcpCliSock, addr = tcpSerSock.accept() 来接受连接。

关于python - HTTP 代理服务器 python [客户端帮助],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060303/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com