websocket和SSE通信示例(无需安装任何插件)

websocket和SSE通信示例(无需安装任何插件)

源码示例(两种方案任意切换)

data(){
	return {
	      heartBeatInterval:5000,// 心跳间隔时间,单位为毫秒
	      webSocket:null,
	      heartBeatTimer:null,
	}
},
mounted() {
    // this.initWebSocket();//方案1,全双工通信websocket,部署线上后要使用wss,要求线上是域名且为https
    this.createSseConnect();//方案2,sse,单工通信(http长连接)
  },
  methods:{
    // sse建立连接
   createSseConnect(){
      let self = this;
      if(window.EventSource){
        const eventSource = new EventSource(`${this.$sseUrl}/sse/createConnect?clientId=${this.$store.state.user.name}`);
        eventSource.onmessage = (e) =>{
            console.log("msg info:", e.data);
            self.handleMessage(JSON.parse(e.data))
        };
        eventSource.onopen = (e) =>{
           console.log("已建立连接~")
        };
        eventSource.onerror = (e) =>{
          if (e.readyState == EventSource.CLOSED) {
            console.log("连接关闭");
          } else if (eventSource.readyState == EventSource.CONNECTING) {
            console.log("正在重连");
          } else {
            console.log('error', e);
          }
        };
        eventSource.close = (e) =>{
             console.log("连接关闭");
        };
      }else{
        console.log("你的浏览器不支持消息通信~")
      }
      console.log(" 测试 打印")
    },
    handleMessage(data) {
      this.msgContent = data.messageTitle;
      this.messageId = data.messageId;
      this.newMsgCount = data.newInfoCount;
      if(this.msgContent){
        this.showMessagePop = true;
      }
    },
    initWebSocket() {
      this.webSocket = new WebSocket(`${this.$websocketUrl}/websocket/${this.$store.state.user.name}`);
      this.webSocket.onopen = () => {
        // 建立连接后开始发送心跳包
        this.startHeartBeat();
      };
      this.webSocket.onmessage = (event) => {
        // 处理服务器发送的消息
        this.handleMessage(JSON.parse(event.data))
      };
      this.webSocket.onclose = () => {
        console.log('WebSocket连接已关闭');
        // 连接关闭后停止心跳包
        this.stopHeartBeat();   
        // 可根据需要重新连接
        // reconnect();
      };
    },
    startHeartBeat() {
      // 每隔一段时间发送心跳包
      this.heartBeatTimer = setInterval(() => {
        if (this.webSocket.readyState === this.webSocket.OPEN) {
          this.webSocket.send('hello,这是一个心跳包'); // 发送心跳包
        }
      }, this.heartBeatInterval);
    },
    stopHeartBeat() {
      // 停止心跳包发送
      clearInterval(this.heartBeatTimer);
    },
  }

注意事项

使用websocket要注意

  1. websocket一段时间后会自动关闭链接,所以要定时发送心跳包请求检测心跳以保证链接持续有效
  2. 在vue项目中配置代理时要注意target地址是ws协议的target: 'ws://x.x.x.x:8080',
  3. websocket打包部署线上必须走wss,这就要求线上域名为https请求

使用SSE要注意

1.当确认请求地址无误,postman也可以请求通,但是唯独在项目中请求一直pending时,前端可以在devServer中配置compress:false,参数来解决。
2.当本地请求正常,部署到线上之后就一直请求超时,statuscode栏显示已屏蔽mixed-content,让后端在nginx配置中加上buffer相关的配置即可

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值