Swoole从入门到入土(18)——WebSocket服务器[心跳ping]
由于 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,控制帧最大载荷为125bytes且不能拆分
3、代码示例:
1) 发送ping帧
use Swoole\WebSocket\Frame; use Swoole\WebSocket\Server; $server = new Server('127.0.0.1', 9501); $server->on('message', function (Server $server, Frame $frame) { $pingFrame = new Frame; $pingFrame->opcode = WEBSOCKET_OPCODE_PING; $server->push($frame->fd, $pingFrame); }); $server->start();
2) 响应ping帧
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) { if ($frame->opcode == 0x09) { echo "Ping frame received: Code {$frame->opcode}\n"; // 回复 Pong 帧 $pongFrame = new Swoole\WebSocket\Frame; $pongFrame->opcode = WEBSOCKET_OPCODE_PONG; $server->push($frame->fd, $pongFrame); } else { echo "Message received: {$frame->data}\n"; } });
4、关于ping与pong的结论
· 心跳包中可能会携带数据
· 当收到Ping帧的时候需要立即返回一个Pong帧
· 在连接建立之后,随时都可以发送Ping帧
· 心跳是用来测试链接是否存在和对方是否在线
· 在响应Ping帧的的Pong帧中,必须携和被响应的Ping帧中相同的数据
笔者注:目前没有找到用JS websocket发送ping帧的资料,如果哪位大佬有相关的说明,请不吝赐教。
--------------------------- 我是可爱的分割线 ----------------------------
最后博主借地宣传一下,漳州编程小组招新了,这是一个面向漳州青少年信息学/软件设计的学习小组,有意向的同学点击链接,联系我吧。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!