在vue中实现使用webscoket进行心跳检测机制
生活随笔
收集整理的這篇文章主要介紹了
在vue中实现使用webscoket进行心跳检测机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<script>data() {// 心跳--startheartCheck: null,lockReconnect: false, //避免ws重連ws: null,wsUrl: null,// 心跳--end},mounted() {_this.heartCheck = {timeout: 1000, //1分鐘發一次心跳timeoutObj: null,serverTimeoutObj: null,reset: function () {clearTimeout(this.timeoutObj)clearTimeout(this.serverTimeoutObj)return this},start: function () {var self = thisthis.timeoutObj = setTimeout(() => {//這里發送一個心跳,后端收到后,返回一個心跳消息,//onmessage拿到返回的心跳就說明連接正常_this.ws.send('ping')// console.log("ping")self.serverTimeoutObj = setTimeout(() => {//如果超過一定時間還沒重置,說明后端主動斷開了_this.ws.close() //如果onclose會執行reconnect,我們執行ws.close()就行了.如果直接執行reconnect 會觸發onclose導致重連兩次}, self.timeout)}, this.timeout)},}if (!window.WebSocket) {window.WebSocket = window.MozWebSocket}if (window.WebSocket) {_this.wsUrl = 'ws://192.168.3.54:6002/ws?projectSonId=' + localStorage.getItem('edrId')_this.ws = new WebSocket(_this.wsUrl) //接口地址_this.createWebSocket(_this.ws, _this.wsUrl)} else {alert('您的瀏覽器不支持WebSocket協議!')}},methods:{// 創建wscreateWebSocket(ws, url) {try {this.initEventHandle(ws, url)} catch (e) {if (!window.WebSocket) {window.WebSocket = window.MozWebSocket}if (window.WebSocket) {_this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')_this.ws = new WebSocket(_this.wsUrl) //接口地址_this.createWebSocket(_this.ws, _this.wsUrl)} else {alert('您的瀏覽器不支持WebSocket協議!')}}},// 監聽initEventHandle(ws, wsUrl) {let _this = thisws.onclose = function () {if (!window.WebSocket) {window.WebSocket = window.MozWebSocket}if (window.WebSocket) {_this.wsUrl = 'ws://122.14.196.211:8899/ws?projectSonId=' + localStorage.getItem('edrId')_this.ws = new WebSocket(_this.wsUrl) //接口地址_this.createWebSocket(_this.ws, _this.wsUrl)} else {alert('您的瀏覽器不支持WebSocket協議!')}console.log('llws連接關閉!' + new Date().toLocaleString())}ws.onerror = function () {console.log('llws連接錯誤!')}ws.onmessage = function (event) {//如果獲取到消息,心跳檢測重置_this.heartCheck.reset().start() //拿到任何消息都說明當前連接是正常的console.log('llws收到消息啦:' + event.data)// console.log(event.data)console.log(event.data)}ws.onopen = function () {_this.heartCheck.reset().start() //心跳檢測重置console.log('llws連接成功!')}},}
<script/>
?
總結
以上是生活随笔為你收集整理的在vue中实现使用webscoket进行心跳检测机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 窗口比较器
- 下一篇: java按钮倒计时_Hyena-倒计时按