以下是非常标准的HTTP服务器的一部分:
class ConnectionHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self, *args, **kwargs):
print "client_address=", self.client_address
data = "Some Text"
self.send_response(200)
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", len(data))
self.end_headers()
self.wfile.write(data)
class MyHttpServer(object):
def __init__(self, Port=9999, ConnHandler=ConnectionHandler):
self.Port = Port
self.ConnHandler = ConnHandler
self.Server = SocketServer.TCPServer(
('127.0.0.1', self.Port), self.ConnHandler)
self.Server.serve_forever()
if __name__ == "__main__":
DemoServer = MyHttpServer()
这是client.py。它使用urllib3进行keepalive会话:
from urllib3 import HTTPConnectionPool
pool = HTTPConnectionPool('127.0.0.1:9999', maxsize=1)
pool.request('GET', '/connect')
pool.request('GET', '/ping')
pool.request('GET', '/test')
print "pool.num_connections={} pool.num_requests={}".format(
pool.num_connections, pool.num_requests)
当我运行客户端时,它显示pool.num_connections = 1 pool.num_requests = 3,正如预期的那样。但是当我运行服务器时,它显示的是:
client_address= ('127.0.0.1', 34858)
127.0.0.1 - - [09/Jul/2014 01:42:45] "GET /connect HTTP/1.1" 200 -
client_address= ('127.0.0.1', 34859)
127.0.0.1 - - [09/Jul/2014 01:42:45] "GET /ping HTTP/1.1" 200 -
client_address= ('127.0.0.1', 34860)
127.0.0.1 - - [09/Jul/2014 01:42:45] "GET /test HTTP/1.1" 200 -
我不应该在每次请求时都有相同的client_address端口号吗?要么我不理解keepalive连接的概念,要么我做错了。