http/1.1的长连接示例
时间: 2023-10-08 13:03:58 浏览: 39
假设客户端使用的是HTTP/1.1协议,服务器支持长连接,以下是一个简单的示例:
1. 客户端发送HTTP请求:
```
GET /index.html HTTP/1.1
Host: www.example.com
Connection: keep-alive
```
在请求头中指定 "Connection: keep-alive",表示客户端希望与服务器建立长连接。
2. 服务器回复HTTP响应:
```
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1234
Connection: keep-alive
<html>
...
</html>
```
在响应头中同样指定 "Connection: keep-alive",表示服务器同意与客户端建立长连接,并在响应数据后保持连接不关闭。
3. 客户端发送下一个HTTP请求:
```
GET /image.png HTTP/1.1
Host: www.example.com
```
由于之前已经建立了长连接,客户端不需要重新建立连接,直接发送下一个请求即可。
4. 服务器回复下一个HTTP响应:
```
HTTP/1.1 200 OK
Content-Type: image/png
Content-Length: 5678
Connection: keep-alive
<binary data>
```
同样保持连接不关闭,等待客户端下一个请求。
5. 客户端发送关闭连接请求:
```
GET /close HTTP/1.1
Host: www.example.com
Connection: close
```
在请求头中指定 "Connection: close",表示客户端希望关闭连接。
6. 服务器回复关闭连接响应:
```
HTTP/1.1 200 OK
Connection: close
Connection closed.
```
在响应头中同样指定 "Connection: close",表示服务器同意关闭连接。
以上是一个简单的HTTP/1.1长连接示例,其中客户端和服务器通过 "Connection: keep-alive" 表示愿意保持连接不关闭,通过 "Connection: close" 表示愿意关闭连接。