Skip to content

Instantly share code, notes, and snippets.

@riskers riskers/main.md
Last active Feb 2, 2019

Embed
What would you like to do?
关于 websocket 心跳的一些记录

长连接为什么要保持心跳?

websocket心跳是为了让 client 告诉 server 『我还活着,没有掉线』而存在的,否则 server 可能会断掉连接。

国内移动无线网络运营商在链路上一段时间内没有数据通讯后, 会淘汰NAT表中的对应项, 造成链路中断。而国内的运营商一般NAT超时的时间为5分钟,所以通常我们心跳设置的时间间隔为3-5分钟。

一般是 client send ping ,server 返回 pong 保持心跳。

var heartCheck = {
    timeout: 20000,
    timeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
     this.start();
    },
    start: function(){
        this.timeoutObj = setTimeout(function(){
            ws.send("ping");
        }, this.timeout)
    }
}

ws.onopen = function () {
   heartCheck.start();
   
   // other code...
};
ws.onmessage = function (event) {
    heartCheck.reset();
    
    // other code...
}

要不然需要 client setInterval send ping 来保持通道。

@riskers

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.