我用一种 HTTP 服务器制作了一个简单的 python 脚本:
import SocketServer
response = b'HTTP/1.0 200 OK\r\nDate: Mon, 1 Jan 1996 01:01:01 GMT\r\n'
response += b'Content-Type: text/plain\r\nContent-Length: 14\r\n\r\n'
response += b'Hello, world!\n'
class MyTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
while True:
line = self.rfile.readline().strip()
print "{} {}:{} wrote: {}".format(self.connection, self.client_address[0], self.client_address[1], line)
if not line:
self.wfile.write(response)
print 'Sent hello world'
#break
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
现在我启动 ab 通过 1 个连接执行 1 个请求:ab -n1 -c1 http://127.0.0.1:9999/
当我在响应后不关闭连接时,期望客户端在收到我的响应后关闭套接字,就会发生一些奇怪的事情。
Ab 一直通过相同的连接重复发送相同的请求:
~$ python2.7 ./socket_server.py
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: GET / HTTP/1.0
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Host: 127.0.0.1:9999
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: User-Agent: ApacheBench/2.3
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Accept: */*
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote:
Sent hello world
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: GET / HTTP/1.0
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Host: 127.0.0.1:9999
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: User-Agent: ApacheBench/2.3
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Accept: */*
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote:
Sent hello world
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: GET / HTTP/1.0
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Host: 127.0.0.1:9999
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: User-Agent: ApacheBench/2.3
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote: Accept: */*
<socket._socketobject object at 0x1068ca600> 127.0.0.1:64626 wrote:
Sent hello world
...并且它通过同一个套接字无限重复。
我试图从套接字读取原始数据:
import SocketServer
class MyTCPHandler2(SocketServer.BaseRequestHandler):
def handle(self):
while True:
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler2)
server.serve_forever()
Ab 甚至还没有尝试等待响应,它在同一个连接中涌入大量请求。
为什么?它是我在 HTTP 1.0 中重用的某种连接吗?无论第一个 \r\n\r\n 对之后的数据如何,我是否应该始终关闭连接?
尝试重现相同行为的正确 httperf 参数是什么?