【问题标题】:Perform handshake only once只执行一次握手
【发布时间】:2016-05-02 06:00:55
【问题描述】:

我使用urllib.request.urlopen 通过HTTPS 从服务器获取数据。该函数被多次调用到同一个服务器,通常是完全相同的 url。但是,与在初始请求时执行握手的标准 Web 浏览器不同,调用单独的 urlopen(url) 将导致每次调用都进行新的握手。这在高延迟网络上非常很慢。有没有办法执行一次握手并重用现有连接以进行进一步的通信?

我无法修改服务器代码以使用套接字或其他协议。

【问题讨论】:

    标签: python-3.x https handshake urlopen


    【解决方案1】:

    您正在为每个请求打开一个新连接。要重用连接,您需要使用http.client

    >>> import http.client
    >>> conn = http.client.HTTPSConnection("www.python.org")
    >>> conn.request("GET", "/")
    >>> r1 = conn.getresponse()
    >>> print(r1.status, r1.reason)
    200 OK
    >>> data1 = r1.read()  # This will return entire content.
    >>> # The following example demonstrates reading data in chunks.
    >>> conn.request("GET", "/")
    >>> r1 = conn.getresponse()
    >>> while not r1.closed:
    ...     print(r1.read(200)) # 200 bytes
    b'<!doctype html>\n<!--[if"...
    ...
    >>> # Example of an invalid request
    >>> conn.request("GET", "/parrot.spam")
    >>> r2 = conn.getresponse()
    >>> print(r2.status, r2.reason)
    404 Not Found
    >>> data2 = r2.read()
    >>> conn.close()
    

    或者使用推荐的pythonRequests Package,它有session objects,使用持久连接(使用urllib3)。

    【讨论】:

      【解决方案2】:

      您应该为它打开一个流,因为 HTTP/(s) 是无状态的,它为每个连接打开到服务器的新套接字。

      所以这个逻辑没有办法,但我只是四处寻找打开持久连接。我只是看到希望它会有所帮助。它提到了 urllib2

      Persistent HTTPS Connections in Python

      【讨论】:

        猜你喜欢
        • 2016-12-21
        • 1970-01-01
        • 2020-02-05
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多