Python Network Programming 简明教程

Python - Connection Re-use

当客户端向服务器发出有效请求时,它们之间会建立一个临时连接,以便完成发送和接收过程。但是,在有些情况下需要保持连接,因为需要通信的程序之间有自动请求和响应。例如,一个交互式网页。在网页加载后需要提交表单数据或下载其他 CSS 和 JavaScript 组件。需要保持连接,以便更快地执行以及客户端与服务器之间有中断的通信。

When a client makes a valid request to a server, a temporary connection is established between them to complete the sending and receiving process. But there are scenarios where the connection needs to be kept alive as there is need of automatic requests and responses between the programs which are communicating. Take for example an interactive webpage. After the webpage is loaded there is a need of submitting a form data or downloading further CSS and JavaScript components. The connection needs to be kept alive for faster performance and an unbroken communication between the client and the server.

Python 提供 urllib3 模块,其中有方法来处理客户端和服务器之间的连接重用。在以下示例中,我们创建一个连接,并通过使用 GET 请求传递不同的参数来进行多个请求。我们收到多个响应,但我们也会计算在此过程中使用的连接数。正如我们所看到的,连接数没有改变,这意味着连接已被重用。

Python provides urllib3 module which had methods to take care of connection reuse between a client and a server. In the below example we create a connection and make multiple requests by passing different parameters with the GET request. We receive multiple responses but we also count the number of connection that has been used in the process. As we see the number of connection does not change implying the reuse of the connection.

from urllib3 import HTTPConnectionPool

pool = HTTPConnectionPool('ajax.googleapis.com', maxsize=1)
r = pool.request('GET', '/ajax/services/search/web',
                 fields={'q': 'python', 'v': '1.0'})
print 'Response Status:', r.status

# Header of the response
print 'Header: ',r.headers['content-type']

# Content of the response
print 'Python: ',len(r.data)

r = pool.request('GET', '/ajax/services/search/web',
             fields={'q': 'php', 'v': '1.0'})

# Content of the response
print 'php: ',len(r.data)

print 'Number of Connections: ',pool.num_connections

print 'Number of requests: ',pool.num_requests

当我们运行以上程序时,我们得到以下输出:

When we run the above program, we get the following output −

Response Status: 200
Header:  text/javascript; charset=utf-8
Python:  211
php:  211
Number of Connections:  1
Number of requests:  2