menc
V2EX  ›  浏览器

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

  •  1
     
  •   menc · Sep 1, 2015 · 4217 views
    This topic created in 3907 days ago, the information mentioned may be changed or developed.

    我的网速还可以,用浏览器打开测试网页在一两秒全部加载完毕。
    但是我用 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 写的有问题还是浏览器有什么特别的技巧?

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

    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
    
    5 replies    2015-09-01 12:25:02 +08:00
    hyq
        1
    hyq  
       Sep 1, 2015
    有些时候,需要根据服务器返回的 Content-Length ,来读取特定的字节数。服务器不一定会关闭连接返回 eof 的。
    hyq
        2
    hyq  
       Sep 1, 2015   ❤️ 1
    你那样的读取方式,只能等到服务器的连接超时时间,才能返回
    Cloudee
        3
    Cloudee  
       Sep 1, 2015   ❤️ 1
    或者你也可以在请求包头里面加上 Connection: close ,这样服务端传输完之后就会关闭连接了
    menc
        4
    menc  
    OP
       Sep 1, 2015
    @Cloudee 那 https 怎么办?没法在头中加东西啊
    est
        5
    est  
       Sep 1, 2015   ❤️ 1
    @menc https 怎么就没法在头里加东西了?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4934 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 01:06 · PVG 09:06 · LAX 18:06 · JFK 21:06
    ♥ Do have faith in what you're doing.