vue 消息推送 WebSocket

#1、创建WebSocket.js文件
#2、设置链接

const url = "localhost:8080"

#3、方法

class WebSocketClass {
  constructor() {
    this.instance = null;
    this.connect();
  }
  static getInstance() {
    if (!this.instance) {
      this.instance = new WebSocketClass();
    }
    return this.instance;
  }
  // 创建连接
  connect() {
    this.ws = new WebSocket(url);
    this.ws.onopen = e => {
      this.heartCheck();
      this.getMessage();
    };
  }
  // 心跳
  heartCheck() {
    const _this = this;
    // 心跳状态
    this.state = setInterval(() => {
      if (_this.ws.readyState === 1) {
        _this.ws.send("/Heart");
      } else {
        this.closeHandle(); // 重新连接
        console.log("状态未连接");
      }
    }, 60000);
  }
  closeHandle() {
    if (this.state) {
      console.log(`断开,重连websocket`);
      // 清除定时器;
      clearInterval(this.state);
      this.connect(); // 重连
    } else {
      console.log(`websocket手动关闭,或者正在连接`);
    }
  }
  // 收/发信息
  getMessage() {
    this.ws.onmessage = e => {
      if (e.data) {
        const newsData = JSON.parse(e.data);
        // 接收到消息
        console.log(`newsData`);
      }
    };
  }
  // 关闭
  close() {
    this.ws.close();
    console.log("关闭连接");
  }
}

export default WebSocketClass;

#4、消息状态

// readyState
// 0 - 表示连接尚未建立。
// 1 - 表示连接已建立,可以进行通信。
// 2 - 表示连接正在进行关闭。
// 3 - 表示连接已经关闭或者连接不能打开。

#5、调用(加载页面中调用)

import WebSocketClass from "@/utils/websocket.js";
// 创建消息连接
const ws = new WebSocketClass();
ws.getMessage();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值