概述
我们知道HTTP协议采用“请求-应答”模式,当使用普通模式,即非KeepAlive模式时,每个请求/应答客户和服务器都要新建一个连接,完成之后立即断开连接(HTTP协议为无连接的协议);当使用Keep-Alive模式(又称持久连接、连接重用)时,Keep-Alive功能使客户端到服务器端的连接持续有效,当出现对服务器的后继请求时,Keep-Alive功能避免了建立或者重新建立连接。
http 1.0中默认是关闭的,需要在http头加入"Connection: Keep-Alive",才能启用Keep-Alive;http 1.1中默认启用Keep-Alive,如果加入"Connection: close ",才关闭。目前大部分浏览器都是用http1.1协议,也就是说默认都会发起Keep-Alive的连接请求了,所以是否能完成一个完整的Keep-Alive连接就看服务器设置情况。
优点明显:避免了建立/释放连接的开销
benchcore.c中增加:
- 在循环外创建socket,每次重复通过这个socket读写,而不在重新创建socket。
- 前面参数处理,
while((opt=getopt_long(argc,argv,"912Vfrt:p:c:?hk",long_options,&options_index))!=EOF
部分的代码修改。
socket.c中增加
- SO_LINGER 设置为onoff=1,linger=1,进行优雅关闭。
- 使用fcntl设置fd为O_NONBLOCK非阻塞。
核心修改:
原来代码
if (http10 > 1)
strcat(request, "Connection: close\r\n");
/* add empty line at end */
if (http10 > 0)
strcat(request, "\r\n");
// printf("Req=%s\n",request);
修改为
if(http10>1)
{
if (!keep_alive)
strcat(request,"Connection: close\r\n");
else
strcat(request,"Connection: Keep-Alive\r\n");