Vue中 使用 WebSocket

1. WebSocket 简介

前端和后端的交互模式最常见的就是:前端发数据请求,从后端拿到数据后展示到页面中。
如果前端不做操作,后端不能主动向前端推送数据,这也是http协议的缺陷。
一种新的通信协议应运而生 WebSocket,它最大的特点就是服务端可以主动向客户端推送消息,客户端也可以主动向服务端发送消息,实现了真正的平等。
在这里插入图片描述
WebSocket 其他特点:

  1. 建立在 TCP 协议之上,服务器端的实现比较容易;
  2. 与 HTTP 协议有着良好的兼容性;
    默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
  3. 数据格式比较轻量,性能开销小,通信高效;
  4. 可以发送文本,也可以发送二进制数据;
  5. 没有同源限制,客户端可以与任意服务器通信;
  6. 协议标识符是ws(如果加密,则为wss),服务器网址就是 URL;

2. Vue中使用 WebSocket

2.1 vue中使用 WebSocket 注意项

  1. 判断浏览器是否支持 WebSocket;
    在这里插入图片描述
    解决兼容性问题传送门:解决 WebSocket 兼容性
  2. 组件加载的时候 连接websocket,在组件销毁的时候 断开websocket;
  3. 后端接口需要引入 socket 模块,否则不能实现连接;

2.2 完整代码

<template>
  <div class="test">
  </div>
</template>

<script>
  export default {
    
    
    data() {
    
    
      return {
    
    
        websock: null,
      }
    },
    methods: {
    
    
      // 初始化weosocket
      initWebSocket(){
    
     
        if(typeof(WebSocket) === "undefined"){
    
    
          console.log("您的浏览器不支持WebSocket")
        }else{
    
    
          const wsurl = "ws://127.0.0.1:8080";
          // 实例化 WebSocket
          this.websock = new WebSocket(wsurl);
          // 监听 WebSocket 连接
          this.websock.onopen = this.websocketonopen;
          // 监听 WebSocket 错误信息
          this.websock.onerror = this.websocketonerror;
          // 监听 WebSocket 消息
          this.websock.onmessage = this.websocketonmessage;
        
          this.websock.onclose = this.websocketclose;
        }
      },
      // 连接建立之后执行send方法发送数据
      websocketonopen(){
    
    
        console.log("socket连接成功")
        let actions = {
    
    "test":"12345"};
        this.websocketsend(JSON.stringify(actions));
      },
      // 连接建立失败重连
      websocketonerror(){
    
    
        console.log("连接错误");
        this.initWebSocket();
      },
      // 数据接收
      websocketonmessage(e){
    
    
        const resdata = JSON.parse(e.data);
        console.log(resdata);
      },
      // 数据发送
      websocketsend(Data){
    
    
        this.websock.send(Data);
      },
      // 关闭
      websocketclose(e){
    
    
        console.log('WebSocket 断开连接',e);
      },
    },    
    beforeMount() {
    
    
      this.initWebSocket();
    },
    destroyed() {
    
    
      //离开路由之后断开 websocket 连接
      this.websock.close(); 
    },
  }
</script>

猜你喜欢

转载自blog.csdn.net/ZYS10000/article/details/113056868
今日推荐