为什么手动 socket 连接 web 服务器比浏览器慢了这么多??

2015-09-01 10:30:38 +08:00
 menc
我的网速还可以,用浏览器打开测试网页在一两秒全部加载完毕。
但是我用 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.cn
using 30.76000s get receive from: i.sso.sina.com.cn

请问这是怎么回事?我的 socket 写的有问题还是浏览器有什么特别的技巧?

相关代码在下面,略去无关代码:

```python

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

```
3668 次点击
所在节点    浏览器
5 条回复
hyq
2015-09-01 11:16:08 +08:00
有些时候,需要根据服务器返回的 Content-Length ,来读取特定的字节数。服务器不一定会关闭连接返回 eof 的。
hyq
2015-09-01 11:17:13 +08:00
你那样的读取方式,只能等到服务器的连接超时时间,才能返回
Cloudee
2015-09-01 11:24:16 +08:00
或者你也可以在请求包头里面加上 Connection: close ,这样服务端传输完之后就会关闭连接了
menc
2015-09-01 11:31:52 +08:00
@Cloudee 那 https 怎么办?没法在头中加东西啊
est
2015-09-01 12:25:02 +08:00
@menc https 怎么就没法在头里加东西了?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/217493

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX