linux - 关于HTTP消息头中Connection是Keep-Alive的一个问题
PHPz
PHPz 2017-04-17 11:43:24
0
1
697

问一个应该是很基础的问题
在我调查的代码中,HttpServer是按照如下方法实现的:

1.用socket()产生socket fd(1),用bind()将socket fd(1)与指定IP:port绑定后,用listen()监听此socket fd(1)。
2.用FD_SET()将sokcet fd(1)加入fdset,用select()监听此fd是否被修改。select()返回后调用accept()accept()的返回值表示新建立的连接的socket fd(2),然后在新线程中用recv()接收此socket中的数据。
3.第2步循环执行

我有一个不明白的地方:
如果client A向server发送的第一个消息头中Connection是Keep-Alive,那么接收到client A的第二条消息是不是对socket fd(1)没有影响,也就是说select()应该继续阻塞,直到新的client请求建立连接。

PHPz
PHPz

学习是最好的投资!

reply all(1)
刘奇

keepalive just tells the server that this connection is a long connection, and the server will not actively close the connection before the connection times out (generally the server can configure this parameter, similar to the Kepalive.timeout parameter), that is Says the client can reuse the connection.

你不明白的地方 It should be that if clientA does not reconnect when sending a message for the second time, a socket fd(1) will still be used, otherwise a new socket fd(2) will be created. In other words, the client has the initiative whether to reuse the keepalive tcp connection. You can use packet capture (tcpdump, etc.) to see the sending situation when reconnecting and not reconnecting.

Just use curl to do an experiment and you will know.

1. Execute two curl commands twice in a row. It is obvious that the connection will be established each time
curl -v -o /dev/null http://www.baidu.com
curl -v -o /dev/null http://www.baidu.com

By capturing packets, you will also find that the three-way handshake occurs every time, that is, the connection is established twice.

2. Request resources from the same server twice at once
curl -v -o /dev/null http://www.baidu.com -o /dev/null http://www.baidu.com

If you capture the packet, you will find that there is only one three-way handshake, that is, the connection is established once. In addition, curl will also give a prompt to reuse the connection
Re-using existing connection! (#0) with host www.baidu.com

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template