Swoole从入门到入土(18)——WebSocket服务器[心跳ping]

因为 WebSocket 是长链接,若是必定时间内没有通信,链接可能会断开。这时候须要心跳机制,WebSocket 协议包含了 Ping 和 Pong 两个帧,能够定时发送 Ping 帧来保持长链接。php

一、心跳原理图:web

 

 

 二、websocket协议控制帧描述编程

Control frames are identified by opcodes where the most significant bit of the opcode is 1.websocket

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.less

Control frames are used to communicate state about the WebSocket.socket

Control frames can be interjected in the middle of a fragmented message.ide

All control frames MUST have a payload length of 125 bytes or less and MUST NOT be fragmented.学习

从原文可知,Ping的协议头是0x9,Pong的协议头是0xA,控制帧最大载荷为125bytes且不能拆分测试

 

三、代码示例:spa

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";
    }
});

 

四、关于ping与pong的结论

· 心跳包中可能会携带数据
· 当收到Ping帧的时候须要当即返回一个Pong帧
· 在链接创建以后,随时均可以发送Ping帧
· 心跳是用来测试连接是否存在和对方是否在线
· 在响应Ping帧的的Pong帧中,必须携和被响应的Ping帧中相同的数据

 

笔者注:目前没有找到用JS websocket发送ping帧的资料,若是哪位大佬有相关的说明,请不吝赐教。

 

---------------------------  我是可爱的分割线  ----------------------------

最后博主借地宣传一下,漳州编程小组招新了,这是一个面向漳州青少年信息学/软件设计的学习小组,有意向的同窗点击连接,联系我吧。

相关文章
相关标签/搜索