在vue中使用websocket

封装

根据项目的目录结构,在相应的文件夹下创建一个js文件,用来封装一个websocket类,假如项目中用到js的地方很多,最好把文件放在全局公共文件夹中;

export class WS{

  constructor(config) {

    this.ws = null;

    this.url = null;

    this.config = config;

    this.socketLink(config)

  }

 

  socketLink(config) {

    // console.log(config);

    this.url = config.url;

    this.createWebSocket(this.url);

  }

  

  createWebSocket(url) {

    try {

      if ('WebSocket' in window) {

        this.ws = new WebSocket(url, 'echo-protocol');

      } else if ('MozWebSocket' in window) {

        this.ws = new MozWebSocket(url, 'echo-protocol');

      } else {

        alert("您的浏览器不支持websocket")

      }

      this.initWebSocket();

    } catch (e) {

      // this.reconnect(url);

      console.log(e);

    }

  }

 

  initWebSocket() {

    this.ws.onclose = () =>{
    
      window.alert("websocket连接关闭!")

    };

    this.ws.onerror = () => {

      window.alert("websocket连接错误!")

    };

    this.ws.onopen =  () => {

      window.alert(this.config.url +  '连接成功')

    };

    this.ws.onmessage = (event) => {

      if(event.data){

        this.config.getMsg(event.data)

      }

    };

  }
  
  //如果需要向服务器发送消息,可以通过调用这个函数实现
  sendWebSocket (agentData) {

    // 添加状态判断,当为OPEN时,发送消息

    if (this.ws.readyState === this.ws.OPEN) { // 1

      let params = JSON.stringify(agentData)

    }else if (this.ws.readyState === this.ws.CLOSED) { // 3
      
      window.alert('websocket连接异常!')

    }else{

      window.alert("not OPEN")

    }

  }

 //如果有重复连接的需要可以加个定时器,在连接失败时再次连接

   reconnect(url) {

    setTimeout(()=> {

      this.createWebSocket(url);

    }, 2000);

  }

}

使用

在需要创建websocket连接的地方引入这类,并初始化(这里是vue3)

import {WS} from '@/config/websocket/websocket.js' 
const socketInstance = ref({})
//websocket配置
const config = {
  url:'http://xxx',
  getMsg: (val) => {
    //接收到返回的message
    const resInfo = JSON.parse(val)
    
    //to do ...

    }
}

//发送消息msg
socketInstance.sendWebSocket(msg)

猜你喜欢

转载自blog.csdn.net/m0_52276756/article/details/130426529
今日推荐