vuecli3.0中使用HTML5 服务器发送事件(Server-Sent Events)--sse,实现前后端单项通讯以及使用webScoket实现双向通讯

SSE单向通讯(serve-client)

参考连接:https://www.iteye.com/blog/jamie-wang-1849193https://blog.csdn.net/qq_35067322/article/details/100022160?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-11.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-11.nonecase

sse对象的详细配置

created() {
    if ("EventSource" in window) {
      const that = this
      var source = new EventSource(requestObj.default.BASE_URL + "pushHazard", {
        withCredentials: true
      });
      source.onmessage = function(e) {
        console.log(e)
      };
      source.onopen = function(e) {};
      source.onerror = function(e) {
        if (e.readyState == EventSource.CLOSED) {
        } else {
          // console.log("onerror:" + e.readyState);
        }
      };
      // source.close();
    } else {
      console.log("没有sse");
    };
  },

webScoket双向通讯(参考:https://zhengkai.blog.csdn.net/article/details/91552993https://zhengkai.blog.csdn.net/article/details/91552993

data(){
    return {
        path: 'ws://192.168.3.70:6002',
        socket: '',
    }
},
methods: {
    initWeb() {
      if (typeof WebSocket === 'undefined') {
        alert('您的浏览器不支持socket')
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path)  //path实在data中定义的地址
        console.log(this.socket)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log('socket连接成功')
    },
    error: function () {
      console.log('连接错误')
    },
    getMessage: function (msg) {
      console.log(msg.data)
    },
    send: function () {
      this.socket.send(params)
    },
    close: function () {
      console.log('socket已经关闭')
    },
}

遇到的问题:之前后台接口使用的是6000端口,在谷歌浏览器上连接失败,报"SecurityError: Failed to construct 'WebSocket': The port 6000 is not allowed."

原因:谷歌浏览器对某些端口做了限制https://blog.csdn.net/demolw/article/details/82020459,改到其它不受限制端口即可

猜你喜欢

转载自blog.csdn.net/qq_41687299/article/details/107761193