vue使用websocket连接协议和sse使用 长链接

简要描述
websocket连接协议
连接URI
WS协议(使用这种)

WSS协议

新信息通知
{
“code”: 200, //状态码 200-监控信息变动
“message”: “监控信息变动”, //信息
“moduleId”: 1, //变动的模块id
“time”: 1642757761000 //当前系统时间(unix毫秒级时间戳)
}

  created() {
     this.initWebSocket();//webscorket 
  },
 destroyed() {
      this.websock.close() //离开路由之后断开websocket连接
    },
     methods: {
     initWebSocket(){ //初始化weosocket
        const wsuri = " WS协议(使用这种)";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        let actions = {"test":"12345"};
        this.websocketsend(JSON.stringify(actions));
      },
      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
        const redata =JSON.parse(e.data)
        // console.log(redata,'32432423432');
        this.idPass=redata.moduleId
            console.log(redata.moduleId,'现在的id')
        
      },
      websocketsend(Data){//数据发送
        this.websock.send(Data);
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
  },

sse使用

created(){
this.sse()
},
methods:{
 sse() {
      // 检查浏览器是否支持SSE
     var supid=JSON.parse(window.sessionStorage.getItem('supid'))
      if ("EventSource" in window) {
        var source = new EventSource(
         "路径ip"
        );
        source.onmessage = function(e) {
          //监听信息的传输
  
         if(e.data=='领导人大屏数据变动'){
         window.sessionStorage.setItem("dataes",JSON.stringify(e.data) );
     
         }
        

          origin = e.origin;
        };

        source.onopen = function(e) {
          //当连接正式建立时触发
          console.log("连接打开.");
        };

        source.onerror = function(e) {
          //当连接发生error时触发
          if (e.readyState == EventSource.CLOSED) {
            console.log("连接关闭");
          } else {
            console.log("onerror:" + e.readyState);
          }
        };
      } else {
        console.log("没有sse");
      }
    },
    }

你可能感兴趣的:(笔记,websocket,网络协议,网络)