
我的网速还可以,用浏览器打开测试网页在一两秒全部加载完毕。
但是我用 socket 转发浏览器的请求,从 socket.sendall ()结束开始算起,到 recv 完毕,花费的时间却数十倍于浏览器:
using 60.132000s get receive from: cdn.v2ex.com
using 46.560000s get receive from: zone.wooyun.org
using 30.46000s get receive from: sjs.sinajs.cnbr> using 30.76000s get receive from: i.sso.sina.com.cn
请问这是怎么回事?我的 socket 写的有问题还是浏览器有什么特别的技巧?
相关代码在下面,略去无关代码:
def recv_basic (the_socket ): total_data='' while True: data = the_socket.recv (2048 ) if not data: break total_data+=data return total_data # ...send codes... t1 = datetime.datetime.now () data2reply = recv_basic (remote ) t2 = datetime.datetime.now () print 'using ', str ((t2 - t1 ).seconds )+'.'+str ((t2-t1 ).microseconds ), 's get receive from:' , remoteAddr 1 hyq 2015-09-01 11:16:08 +08:00 有些时候,需要根据服务器返回的 Content-Length ,来读取特定的字节数。服务器不一定会关闭连接返回 eof 的。 |
2 hyq 2015-09-01 11:17:13 +08:00 你那样的读取方式,只能等到服务器的连接超时时间,才能返回 |
3 Cloudee 2015-09-01 11:24:16 +08:00 或者你也可以在请求包头里面加上 Connection: close ,这样服务端传输完之后就会关闭连接了 |