VUE中实现WEBSOCKET前后端通讯

  1. 在Vue项目中安装WebSocket库
//npm install --save websocket
npm install --save vue-native-websocket
  1. main.js全局配置
import websocket from 'vue-native-websocket';
Vue.use(websocket, '', {
    
    
    connectManually: true, // 手动连接
    format: 'json', // json格式
    reconnection: true, // 是否自动重连
    reconnectionAttempts: 5, // 自动重连次数
    reconnectionDelay: 2000, // 重连间隔时间
});
  1. 创建WebSocket连接
export default {
    
    
  data() {
    
    
    return {
    
    
      socket:null,
    }
  },
  mounted() {
    
    
    if(this.socket){
    
    
      this.socket.close()
       console.log('socket关闭1')
     }
  },
  created() {
    
    
  	
  },
  destroyed() {
    
    
    if(this.socket){
    
    
      this.socket.close() //离开路由之后断开websocket连接
       console.log('socket关闭1')
     }
  },
  methods: {
    
    
    initWebSocket() {
    
    
      if (typeof WebSocket === "undefined") {
    
    
        alert("您的浏览器不支持socket");
      } else {
    
    
        let WSUrl = ‘ws://10.0.0.121:8700/camera/ws’;
        // 实例化socket
        this.socket = new WebSocket(`${
      
      WSUrl}`);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onsend = this.send;
        // 关闭cocket
        this.socket.onclose = this.close;
      }
    },
    open() {
    
    
      //连接建立之后执行send方法发送数据
      this.socket.send(JSON.stringify({
    
    "app": "start"}));
      console.log("socket连接成功");
    },
    error() {
    
    
      //连接建立失败重连
      console.log("连接错误");
      this.socket = null;
      const timer = setTimeout(() => {
    
    
        this.initWebSocket();
        this.WS.wsCount++;
      }, 5000);
      if (this.WS.wsCount > 4) {
    
    
        clearTimeout(timer);
      }
    },
    getMessage(msg) {
    
    
      //数据接收
      console.log(JSON.parse(msg.data));
    },
    send(Data) {
    
    
      console.log('数据发送')
	  //数据发送
	  this.websock.send(Data)
    },
    close() {
    
    
      console.log("socket已经关闭");
    },
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_43883951/article/details/131211221