vue封装websocket兼心跳检测

创建socker.js文件, 放在utils文件夹下

socket.js

var ws= null; //建立的连接
var lockReconnect= false;//是否真正建立连接
var timeout= 3*1000;//30秒一次心跳
var timeoutObj= null;//心跳心跳倒计时
var serverTimeoutObj= null;//心跳倒计时
var timeoutnum= null;//断开 重连倒计时
var global_callback = null; //监听服务端消息
// uri: 长链接地址
// jwt: 前后端连接凭证, 按需添加
// callback: 服务端消息回调函数 export function createWebscoket(uri, jwt, callback) { global_callback = callback ws = new WebSocket(uri, [jwt]) ws.onopen = ()=>{ lockReconnect = true //开启连接心跳 start() } ws.onmessage = onMessage ws.onerror = onError ws.onclose = onClose ws.onsend = onSend } //发送消息 export function onSend(message){ console.log(`发送消息: ${message}`) ws.send(message) } //接受服务端消息 export function onMessage(res){ let msgData = res.data if (typeof msgData != 'object' && msgData != 'Connect success') { var data = msgData.replace(/\ufeff/g, ""); var message = JSON.parse(data) //服务端消息回掉 global_callback(message) //重置心跳 reset() } } //连接失败 export function onError(){ console.log('连接失败') ws.close() ws = null lockReconnect = false } //连接关闭 export function onClose(){ console.log('连接关闭') } //断开关闭 export function closeWs(){ if(lockReconnect) { ws.close() ws = null lockReconnect = false } } // 发送心跳 export function start () { timeoutObj && clearTimeout(timeoutObj); serverTimeoutObj && clearTimeout(serverTimeoutObj); timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息 if (ws.readyState == 1) { //如果连接正常 ws.send(JSON.stringify({ "action": "ROOM_KEEP_CONNECTION" })); } else{ //否则重连 reconnect() } serverTimeoutObj = setTimeout(function() { //超时关闭 ws.close(); }, timeout ); }, timeout+ 3000) } //重置心跳 export function reset(){ var that = this; //清除时间 clearTimeout(timeoutObj); //清除时间 clearTimeout(serverTimeoutObj); start(); //重启心跳 } //重新连接 export function reconnect() { if(lockReconnect) { return; }; lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 timeoutnum && clearTimeout(timeoutnum); timeoutnum = setTimeout(function () { createWebscoket();//新连接 lockReconnect = false; },5000); }

  

页面或组件内调用:

  

import { createWebscoket, onSend, closeWs } from '@/utils/socket.js'

data(){
    return {
      socketMsg: ''
    }
},

created(){
    this.initWebsocket() 
},

methods: {
  //连接socket
    initWebsocket() {
      createWebscoket(uri, this.jwt, this.messagesCallBack)
    },
   //新消息监听
   messagesCallBack(msg){
      this.socketMsg = msg
   },
   
   //发送socket消息到服务器
  sendMessage(){
     onSend(JSON.stringift({
       data: '要发送的消息'
      }))
   },
   //断开socket
   closeWs(){
      closeWs()
   }    
    
}

  

 

posted @ 2022-09-30 11:21  yanghaogogogo  阅读(880)  评论(1编辑  收藏  举报