[英]sock.recv() is taking too much time to execute in the python code
Following is the code which listens on a port for HTTP requests and sends the request packet to the server running on port 80, gets the response and sends the data back to the client. 以下是在端口上侦听HTTP请求并将请求数据包发送到在端口80上运行的服务器,获取响应并将数据发送回客户端的代码。 Now, everything is executing fine but the following line of code :
现在,一切正常,但以下代码行:
data = req_soc.recv(1024)
is taking too much time to execute and I have observed that, it takes long time to execute when it is going to/has received the last packet. 我花了太多时间执行,而且我观察到,当它要/已经收到最后一个数据包时,要花很长时间才能执行。 I have also tried the same code using
select.select()
but the results are the same. 我也使用
select.select()
尝试了相同的代码,但结果是相同的。 Since I want to handle the data (raw) that is coming from the client and the actual HTTP server, I have no other choice than using sockets. 由于我想处理来自客户端和实际HTTP服务器的数据(原始),因此我没有其他选择,只能使用套接字。
import socket
import thread
def handle_client(client):
data = client.recv(512)
request = ''
request += data
print data
print '-'*20
spl = data.split("\r\n")
print spl[0]
print spl[1]
if len(request):
req_soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
req_soc.connect(('localhost', 80))
req_soc.send(request)
response = ''
data = req_soc.recv(1024)
while data:
response += data
print 1
data = req_soc.recv(1024)
req_soc.close()
print response
if len(response):
client.send(response)
client.close()
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('localhost', 4422))
server.listen(5)
print("Server is running...\n")
MSGLEN = 1024
while 1:
client, address = server.accept()
thread.start_new_thread(handle_client, (client, ))
Clients can do multiple commands (eg: GET) within one connection. 客户端可以在一个连接中执行多个命令(例如:GET)。 You cannot wait for the client to send all the commands because based on what you return it could request more (eg: images of a web page).
您不能等待客户端发送所有命令,因为根据您返回的内容,客户端可能会请求更多命令(例如:网页图像)。 You have to parse the parts (commands) of request, find the boundary, forward that request to the server and write back the answer to the client.
您必须解析请求的各个部分(命令),找到边界,将该请求转发到服务器,然后将答案写回客户端。 All this in a way that doesn't block on reading the client.
所有这些都不会妨碍读取客户端。
I'm not sure what's the best way to do this in python , but if you spend 5 minutes of googling you'll find a perfect HTTP proxy library. 我不知道什么是在Python做到这一点的最好方式,但是如果你花上5分钟时间谷歌搜索,你会发现一个完美的HTTP代理库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.