• 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 SwooleWebSocketFrame;
    use SwooleWebSocketServer;
    
    $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 (SwooleWebSocketServer $server, $frame) {
        if ($frame->opcode == 0x09) {
            echo "Ping frame received: Code {$frame->opcode}
    ";
            // 回复 Pong 帧
            $pongFrame = new SwooleWebSocketFrame;
            $pongFrame->opcode = WEBSOCKET_OPCODE_PONG;
            $server->push($frame->fd, $pongFrame);
        } else {
            echo "Message received: {$frame->data}
    ";
        }
    });

    4、关于ping与pong的结论

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

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

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

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

  • 相关阅读:
    C语言指针的一些题目
    PowerDesigner 物理数据模型(PDM)
    PowerDesigner概念数据模型 CDM
    加密狗原理介绍
    磐石加密狗NT88管理层API
    使用加密狗进行加密的一些策略
    让 PowerDesigner 支持 SQLite!
    防止用户重复登陆
    SQL Server里一些未公开的扩展存储过程
    14个数据库的设计技巧
  • 原文地址:https://www.cnblogs.com/ddcoder/p/14137223.html
Copyright © 2020-2023  润新知