使用 urllib2 加载 URL 时如何设置 TCP_NODELAY 标志? [英] How to set TCP_NODELAY flag when loading URL with urllib2?

查看:15
本文介绍了使用 urllib2 加载 URL 时如何设置 TCP_NODELAY 标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 urllib2 加载网页,我的代码是:

I am using urllib2 for loading web-page, my code is:

httpRequest = urllib2.Request("http:/www....com")
pageContent = urllib2.urlopen(httpRequest)
pageContent.readline()

如何获取套接字属性来设置TCP_NODELAY?

How can I get hold of the socket properties to set TCP_NODELAY?

在普通套接字中,我将使用函数:

In normal socket I would be using function:

socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

推荐答案

如果您需要访问所用套接字上的此类低级属性,则必须重载某些对象.

If you need to access to such low level property on the socket used, you'll have to overload some objects.

首先,您需要创建 HTTPHandler,在标准库中这样做:

First, you'll need to create a subclass of HTTPHandler, that in the standard library do :

class HTTPHandler(AbstractHTTPHandler):

    def http_open(self, req):
        return self.do_open(httplib.HTTPConnection, req)

    http_request = AbstractHTTPHandler.do_request_

如您所见,它使用 HTTPConnection 来打开连接...您也必须覆盖它 ;) 以升级 connect() 方法.

As you can see, it uses a HTTPConnection to open connection... You'll have to override it too ;) to upgrade the connect() method.

这样的事情应该是一个好的开始:

Something like this should be a good start :

class LowLevelHTTPConnection(httplib.HTTPConnection):

    def connect(self):
        httplib.HTTPConnection.connect(self)
        self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)


class LowLevelHTTPHandler(HTTPHandler):

    def http_open(self, req):
        return self.do_open(LowLevelHTTPConnection, req)

urllib2 足够聪明,可以让你子类化一些处理程序然后使用它,urllib2.build_opener 是为此而设计的:

urllib2 is smart enough to allow you to subclass some handler and then use it, the urllib2.build_opener is made for this :

urllib2.install_opener(urllib2.build_opener(LowLevelHTTPHandler)) # tell urllib2 to use your HTTPHandler in replacement of the standard HTTPHandler
httpRequest = urllib2.Request("http:/www....com")
pageContent = urllib2.urlopen(httpRequest)
pageContent.readline()

这篇关于使用 urllib2 加载 URL 时如何设置 TCP_NODELAY 标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆