我正在使用python中的一个简单代理,它从浏览器接收HTTP GET
请求,查询正确的网站并将数据(html,css,photos)返回给客户端。我有它工作,但是从外部Web服务器读取数据并将其发送回客户端需要花费大量时间。以下是(我认为)相关代码:
tempSocket.send(requestToWebpage)
tempList = []
while 1:
print "waiting for data from website..."
data = tempSocket.recv(bufferSize)
if not data:
break
else:
tempList.append(data)
tempResponse = ''.join(tempList)
print "closing temp socket..."
tempSocket.close()
splitResponse = tempResponse.partition("\r\n")
response = splitResponse[0] + "\r\n" + "Proxy-connection: close\r\n" + splitResponse[2]
print "sending results back..."
newConnection.send(response)
newConnection.close()
代理程序在我自己的计算机上运行(与客户端浏览器一样),即Windows 7 64位。我有一个不错的无线连接到互联网。目前,接收每个GET请求的结果并将其传输到客户端需要花费几分钟的时间。通过观看打印语句,我注意到大部分时间似乎是在while循环中花费(特别是最后一个循环),但是其他打印消息也会比看起来应该更长。
有关正在发生的事情以及提高速度的建议吗?
答案 0 :(得分:1)
马库斯的评论可能是正确的。远程服务器没有关闭其连接。
你可能会要求这种行为,也许甚至没有意识到这一点。对服务器的请求是什么,即requestToWebpage
中发送的是什么?您是否设置了Connection: Keep-Alive
标题?
如果您在请求中使用HTTP 1.1,则Keep-Alive是默认值。
如果不是因为Keep-Alive,你可能需要从回复中获取Content-Length,然后你就会知道要读取多少字节。