WebSocket加入心跳包防止自动断开连接

近日,在公司中开发一个使用websocket为前端推送消息的功能时,发现一个问题:就是每隔一段时间如果不传送数据的话,与前段的连接就会自动断开;

刚开始以为是session的原因,因为web session 的默认时间是30分钟;但是通过日志发现断开时间间隔时间远远不到30分钟;认真分析发现不操作间隔恰好为90秒

它就会在自动断开;随恍然大悟;原来是我们的使用nginx 代理,nginx配置了访问超时时间为90s;

WebSocket是html5中用来实现长连接的一个协议。
在同时使用nginx反向代理和websocket的时候,因为websocket的通信管道必须都要一直处于开启状态。

proxy_read_timeout 90;

解决方案:

1. 修改nginx配置
nginx 通过在客户端和后端服务器之间建立起一条隧道来支持WebSocket。
为了使nginx可以将来自客户端的Upgrade请求发送给后端服务器,Upgrade和Connection的头信息必须被显式的设置。如下所示:

location /web/count {
        proxy_pass http://tomcat-server;
        proxy_redirect off;
        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    
}

一旦我们完成以上设置,nginx就可以处理WebSocket连接了。
注意,必须要有

proxy_set_header Host $host:$server_port;   

这个配置
否则,会报:
WebSocket connection to 'ws://192.168.1.104:9080/web/count' failed: Error during WebSocket handshake: Unexpected response code: 403的错误

2. 也可以在前端页面也添加心跳机制保持连接。

var userId=$("#userId").val();
var lockReconnect = false;  //避免ws重复连接
var ws = null;          // 判断当前浏览器是否支持WebSocket
var wsUrl = serverConfig.cyberhouse_ws+userId;
createWebSocket(wsUrl);   //连接ws

function createWebSocket(url) {
    try{
        if('WebSocket' in window){
            ws = new WebSocket(url);
        }else if('MozWebSocket' in window){  
            ws = new MozWebSocket(url);
        }else{
            layui.use(['layer'],function(){
              var layer = layui.layer;
              layer.alert("您的浏览器不支持websocket协议,建议使用新版谷歌、火狐等浏览器,请勿使用IE10以下浏览器,360浏览器请使用极速模式,不要使用兼容模式!"); 
            });
        }
        initEventHandle();
    }catch(e){
        reconnect(url);
        console.log(e);
    }     
}

function initEventHandle() {
    ws.onclose = function () {
        reconnect(wsUrl);
        console.log("llws连接关闭!"+new Date().toUTCString());
    };
    ws.onerror = function () {
        reconnect(wsUrl);
        console.log("llws连接错误!");
    };
    ws.onopen = function () {
        heartCheck.reset().start();      //心跳检测重置
        console.log("llws连接成功!"+new Date().toUTCString());
    };
    ws.onmessage = function (event) {    //如果获取到消息,心跳检测重置
        heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
        console.log("llws收到消息啦:" +event.data);
        if(event.data!='pong'){
            var obj=eval("("+event.data+")");
            layui.use(['layim'], function(layim){
                if(obj.type=="onlineStatus"){
                    layim.setFriendStatus(obj.id, obj.content);
                }else if(obj.type=="friend" || obj.type=="group"){
                    layim.getMessage(obj);  
                } 
    };
}
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
    ws.close();
}  

function reconnect(url) {
    if(lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {     //没连接上会一直重连,设置延迟避免请求过多
        createWebSocket(url);
        lockReconnect = false;
    }, 2000);
}

//心跳检测
var heartCheck = {
    timeout: 540000,        //9分钟发一次心跳
    timeoutObj: null,
    serverTimeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
    },
    start: function(){
        var self = this;
        this.timeoutObj = setTimeout(function(){
            //这里发送一个心跳,后端收到后,返回一个心跳消息,
            //onmessage拿到返回的心跳就说明连接正常
            ws.send("ping");
            console.log("ping!")
            self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了
                ws.close();     //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
            }, self.timeout)
        }, this.timeout)
    }
}
// 收到客户端消息后调用的方法 
    @OnMessage  
    public void onMessage(String message, Session session) {  
        if(message.equals("ping")){
        }else{
        。。。。
        }
   }

系统发现websocket每隔10分钟自动断开连接,搜了很多博客都说设置一下nginx的
keepalive_timeout
proxy_connect_timeout
proxy_send_timeout
proxy_read_timeout
这四个字段的时长即可,然而好像并不奏效。遂采取心跳包的方式每隔9分钟客户端自动发送ping消息给服务端,服务端不需要返回。即可解决问题。



作者:一行代码一首诗
链接:https://www.jianshu.com/p/1141dcf6de3e
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Java 中使用 WebSocket 发送心跳包可以通过以下步骤实现: 1. 创建一个定时器,在一定的时间间隔内发送心跳包。 2. 在 WebSocket 连接建立时启动定时器。 3. 在定时器中发送一个特定的消息,表示心跳包。 下面是一个简单的示例代码,用于在 Java 中使用 WebSocket 发送心跳包: ```java import javax.websocket.*; import java.net.URI; import java.util.Timer; import java.util.TimerTask; @ClientEndpoint public class WebSocketClient { private Timer timer; @OnOpen public void onOpen(Session session) { System.out.println("WebSocket connected!"); // 启动定时器,每隔一段时间发送心跳包 timer = new Timer(); timer.schedule(new HeartbeatTask(session), 0, 5000); } @OnMessage public void onMessage(String message) { System.out.println("Received message: " + message); } @OnError public void onError(Throwable throwable) { System.out.println("Error: " + throwable.getMessage()); } @OnClose public void onClose() { System.out.println("WebSocket closed!"); } private static class HeartbeatTask extends TimerTask { private final Session session; public HeartbeatTask(Session session) { this.session = session; } @Override public void run() { try { System.out.println("Sending heartbeat message..."); session.getBasicRemote().sendText("heartbeat"); } catch (Exception ex) { ex.printStackTrace(); } } } public static void main(String[] args) throws Exception { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(WebSocketClient.class, new URI("ws://localhost:8080/ws")); } } ``` 在上面的示例代码中,我们创建了一个 `WebSocketClient` 类,用于与 WebSocket 服务器进行通信。在 `onOpen` 方法中,我们启动了一个定时器,并设置定时器每隔 5 秒发送一个心跳包。在 `HeartbeatTask` 类中,我们定义了发送心跳包的具体实现。最后,在 `main` 方法中,我们使用 `WebSocketContainer` 来连接到 WebSocket 服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值