[前端]Typescript单例模式实现websocket通信

[前端]Typescript单例模式实现websocket通信

/**
 * 定义回调函数
 * @author ERRUI
 */
class SocketService {
  static instance: any = null;

  /**
   * 单例模式
   */
  static get Instance() {
    if (SocketService.instance) {
      return SocketService.instance;
    }
    return (SocketService.instance = new SocketService());
  }
  // 和服务端连接的socket对象
  ws: any = null;

  // 存储回调函数
  callBackMapping = {};

  // 标识是否连接成功
  connected = false;

  // 记录重试的次数
  sendRetryCount = 0;

  // 重新连接尝试的次数
  connectRetryCount = 0;
  /**
   * 心跳检测机制:20秒发一个检测消息过去
   */
  sendFixHeart() {
    let sendFixHeartTimer: any = null;
    clearInterval(sendFixHeartTimer);
    sendFixHeartTimer = setInterval(() => {
      this.ws.send(JSON.stringify({}));
    }, 20000);
  }
  /**
   * websocket连接
   */
  connect() {
    // 连接服务器
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket');
    }
    this.ws = new WebSocket('这里放地址');
    // 连接成功的事件
    this.ws.onopen = () => {
      console.log('连接服务端成功了,ws状态是' + this.ws.readyState);
      this.connected = true;
      // 重置重新连接的次数
      this.connectRetryCount = 0;
      this.sendFixHeart();
    };

    // 当连接成功之后, 服务器关闭的情况 |  连接服务端失败
    this.ws.onclose = () => {
      if (this.connectRetryCount >= 10) {
        this.ws.close();
        console.log('重新连接服务器失败');
      } else {
        this.connected = false;
        this.connectRetryCount++;
        setTimeout(() => {
          this.close();
          this.connect();
          console.log('连接服务端失败第' + this.connectRetryCount + '次,1秒后重试');
        }, 1000);
      }
    };

    // websocket连接错误
    this.ws.onerror = function () {
      console.log('Error,websocket连接错误');
    };
  }
  send(data: any) {
    // 判断此时此刻有没有连接成功
    if (this.connected) {
      this.sendRetryCount = 0;

      this.ws.send(JSON.stringify(data));
    } else {
      this.sendRetryCount++;
      setTimeout(() => {
        this.send(data);
        console.log('已经重新发送第:' + this.sendRetryCount + '次');
      }, 1000);
    }
  }

  /**
   * 关闭websocket连接
   */
  close() {
    this.ws.close();
  }
}
export default SocketService;

  • 在项目中使用(Vue3为例)
<script setup lang="ts">
import { reactive } from 'vue';
import SocketService from '../utils/websocket';

const data = reactive({
  socketServe: SocketService.Instance
});
const socket: any = data.socketServe;

/**
 * 发送请求
 */
function send() {
  socket.send({
    data: { option: 'listen', id: idInt }
  });
}
setTimeout(() => {
  send();
}, 100);
/**
 * 发送数据
 */
socket.connect();
/**
 * 接受信息
 */
socket.ws.onmessage = (msg: { data: any }) => {
  const msgview = JSON.parse(msg.data);
return msgview
};
</script>

最后


文章仅发布在CSDN平台和个人博客中,对本文技术点有疑问欢迎在评论区友好交流。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一ERRUI一

www.errui.net

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值