菜单
Socket数据接口 > API Reference > 发送心跳包
发送心跳包 最近更新时间:2020-10-20 10:31:13

# 流程描述

本流程为客户端向服务端定时发送心跳包。

# 说明

通过执行该流程,服务端认为客户端仍然保持连接;
定时时长不得大于5分钟,如果服务端正确接收到,将返回心跳返回包;
如果没有接收到,服务端将会主动断开连接。

# 流程执行

  •       var timeTask = null;
    /**
     * 每4分钟向服务器发送心跳包
     */
    function scheduleTask(){
        console.log("开始发送心跳包")
        client.write(getHeatBeatMsg());
    }
    
    client.on('data', function(data) {
        const buf = Buffer.from(data,'utf-8')
        const msgType = buf[3]
        const msgLenBuf = Buffer.from([buf[4],buf[5],buf[6],buf[7]])
        const msgLength = msgLenBuf.readInt32BE(0)
        const msgBuf = Buffer.alloc(msgLength)
        buf. copy(msgBuf,0,8,msgLength + 8);
        switch (msgType){
          case 3:
            console.log("接收到服务端发送的同步开始返回包,客户端开始定时发送心跳包")
            timeTask = setInterval(scheduleTask, 1000*60*4)
            break;
          default:
            break;
        }
      });
    
      client.on('close', function() {
        console.log('连接关闭');
        if(timeTask != null){
          clearInterval(timeTask)
        }
        client = net.createConnection(port, host, onConnect);
        client.on('error',onError);
      });
    
    /**
     * 生成心跳包
     */
    function getHeatBeatMsg() {
      const bufHead = Buffer.from([0,0,1,0]);
      const bufMsg = Buffer.alloc(0)
      const buflength = Buffer.alloc(4,0)
      buflength.writeIntBE(bufMsg.length, 0, 4);
      const totalLength = bufHead.length + buflength.length + bufMsg.length;
      return Buffer.concat([bufHead,buflength,bufMsg],totalLength);
    }

# 调用参数

无调用参数。

# 接口响应

服务端返回心跳返回包。

# 响应数据

返回数据类型为字节流,包括包头和包数据,返回的包类型为心跳返回包。

  • 包字节流示例:

00 00 01 01 00 00 00 00

# 响应包头

返回的包头结构表如下所示:

名称类型长度返回值
固定位数字2字节为 00 00
版本号数字1字节为 01
指令码数字1字节为01,心跳返回包,服务端给客户端的心跳返回包
包数据长度数字4字节为包数据段的长度

# 响应包数据

无响应参数