只执行一次握手
Perform handshake only once
我使用 urllib.request.urlopen
通过 HTTPS
从服务器获取数据。该函数被同一台服务器多次调用,通常是完全相同的 url。然而,与在初始请求时执行握手的标准 Web 浏览器不同,调用单独的 urlopen(url)
's 将导致每次调用都进行新的握手。这在高延迟网络上非常 慢。有没有办法执行一次握手并重用现有连接进行进一步通信?
我无法修改服务器代码以使用套接字或其他协议。
您应该为它打开一个流,因为 HTTP/(s) 是无状态的,它会为每个连接打开到服务器的新套接字。
所以这个逻辑没办法,只是四处寻找打开持久连接。我只是看到希望它会有所帮助。它提到了 urllib2
您正在为每个请求打开一个新连接。要重用连接,您需要使用 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, which has session objects that make use of persistent connections (using urllib3).
我使用 urllib.request.urlopen
通过 HTTPS
从服务器获取数据。该函数被同一台服务器多次调用,通常是完全相同的 url。然而,与在初始请求时执行握手的标准 Web 浏览器不同,调用单独的 urlopen(url)
's 将导致每次调用都进行新的握手。这在高延迟网络上非常 慢。有没有办法执行一次握手并重用现有连接进行进一步通信?
我无法修改服务器代码以使用套接字或其他协议。
您应该为它打开一个流,因为 HTTP/(s) 是无状态的,它会为每个连接打开到服务器的新套接字。
所以这个逻辑没办法,只是四处寻找打开持久连接。我只是看到希望它会有所帮助。它提到了 urllib2
您正在为每个请求打开一个新连接。要重用连接,您需要使用 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, which has session objects that make use of persistent connections (using urllib3).