Vue+WebSocket 心跳机制 保持连接
<template> <div></div> </template> <script> export default { data() { return { // websocket websock: null, //建立的连接 lockReconnect: false, //是否真正建立连接 timeout: 28 * 1000, //30秒一次心跳 timeoutObj: null, //心跳心跳倒计时 serverTimeoutObj: null, //心跳倒计时 timeoutnum: null, //断开 重连倒计时 } }, created() { //页面刚进入时开启长连接 this.initWebSocket(); }, destroyed: function () { //页面销毁时关闭长连接 this.websocketclose(); }, methods: { // WebSocket //建立连接 initWebSocket() { //初始化weosocket //const wsuri = "ws://sms.填写您的地址.com/websocket/" + this.charId; //ws地址 const wsuri ="ws://sms.balabala.com/websocket/" + this.$route.query.telphone //建立连接 this.websock = new WebSocket(wsuri); //连接成功 this.websock.onopen = this.websocketonopen; //连接错误 this.websock.onerror = this.websocketonerror; //接收信息 this.websock.onmessage = this.websocketonmessage; //连接关闭 this.websock.onclose = this.websocketclose; }, //重新连接 reconnect() { var that = this; if (that.lockReconnect) { return; } that.lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 that.timeoutnum && clearTimeout(that.timeoutnum); that.timeoutnum = setTimeout(function () { //新连接 that.initWebSocket(); that.lockReconnect = false; }, 5000); }, //重置心跳 reset() { var that = this; //清除时间 clearTimeout(that.timeoutObj); clearTimeout(that.serverTimeoutObj); //重启心跳 that.start(); }, //开启心跳 start() { var self = this; self.timeoutObj && clearTimeout(self.timeoutObj); self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj); self.timeoutObj = setTimeout(function () { //这里发送一个心跳,后端收到后,返回一个心跳消息, if (self.websock.readyState == 1) { //如果连接正常 self.websock.send( '{"toUserId":"' + self.$route.query.telphone + '"}' ); console.log("发送消息"); } else { //否则重连 self.reconnect(); } self.serverTimeoutObj = setTimeout(function () { //超时关闭 self.websock.close(); }, self.timeout); }, self.timeout); }, //连接成功事件 websocketonopen() { //提示成功 console.log("连接成功", 3); //开启心跳 this.start(); }, //连接失败事件 websocketonerror(e) { //错误 console.log("WebSocket连接发生错误"); //错误提示 console.log("Websocket error, Check you internet!"); //重连 this.reconnect(); }, //连接关闭事件 websocketclose(e) { //关闭 console.log("connection closed (" + e + ")"); //提示关闭 console.log("连接已关闭", 3); //重连 this.reconnect(); }, //接收服务器推送的信息 websocketonmessage(event) { //打印收到服务器的内容 //数据接收 let that = this; const redata = JSON.parse(event.data); console.log(redata,"数据接收"); //收到服务器信息,心跳重置 this.reset(); }, //向服务器发送信息 websocketsend(msg) { //数据发送 this.websock.send(msg); }, }, }; </script> <style scoped> </style>