当前位置:   article > 正文

Vue中实现WEBSOCKET前后端通讯_vue websocket前后端交互

vue websocket前后端交互

前言:什么是WebSocket?
WebSocket和http一样,都是一种网络传输协议,但是和Http协议相比,它有一点不同,它可以在单个TCP连接上进行全双工通信,通俗来说就是客户端可以向服务端发送请求,服务端也可以向客户端发送请求;总的来说:http协议服务端响应到客户端是被动的,而webSocket协议服务端请求到客户端是主动的。
这张图网上有很多,完美展示了http和webSocket的区别:
在这里插入图片描述

  1. 在Vue项目中安装WebSocket库
//npm install --save websocket
npm install --save vue-native-websocket
  • 1
  • 2
  1. main.js全局配置
import websocket from 'vue-native-websocket';
Vue.use(websocket, '', {
    connectManually: true, // 手动连接
    format: 'json', // json格式
    reconnection: true, // 是否自动重连
    reconnectionAttempts: 5, // 自动重连次数
    reconnectionDelay: 2000, // 重连间隔时间
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  1. 创建WebSocket连接
export default {
  data() {
    return {
      socket:null,
      WS:{
        wsCount:0
       }
    }
  },
  mounted() {
    this.initWebSocket()
  },
  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.socket.send(Data)
    },
    close() {
      console.log("socket已经关闭");
    },
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/576668
推荐阅读
相关标签
  

闽ICP备14008679号