由于 WebSocket 是长连接,如果一定时间内没有通讯,连接可能会断开。这时候需要心跳机制,WebSocket 协议包含了 Ping 和 Pong 两个帧,可以定时发送 Ping 帧来保持长连接。
1、心跳原理图:

2、websocket协议控制帧描述
Control frames are identified by opcodes where the most significant bit of the opcode is 1.
Currently defined opcodes for control frames include 0x8 (Close), 0x9 (Ping), and 0xA (Pong). Opcodes 0xB-0xF are reserved for further control frames yet to be defined.
Control frames are used to communicate state about the WebSocket.
Control frames can be interjected in the middle of a fragmented message.
All control frames MUST have a payload length of 125 bytes or less and MUST NOT be fragmented.
从原文可知,Ping的协议头是0x9,Pong的协议头是0xA,控制帧最大载荷为125byte

WebSocket协议利用Ping和Pong帧实现长连接的心跳保持。当接收到Ping帧时,服务器需回应Pong帧以确认连接活跃。Swoole示例展示了如何发送和响应这些帧。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



