ts封装websocket

import {
    interval, Subject } from 'rxjs';

export class WebsocketService {
   
  messageSubject; // subject对象,用于发送事件
  url; // 默认请求的url
  webSocket; // websocket对象
  connectSuccess = false; // websocket 连接成功
  period = 10 * 1000; // 10s检查一次
  serverTimeoutSubscription = null; // 定时检测连接对象
  reconnectFlag = false; // 重连
  reconnectPeriod = 5 * 1000; // 重连失败,则5秒钟重连一次
  reconnectSubscription = null; // 重连订阅对象
  runTimeSubscription; // 记录运行连接subscription
  runTimePeriod = 60 * 10000; // 记录运行连接时间
  eventTimestamp = new Date().getTime();

  constructor() {
   
    this.messageSubject = new Subject();
    // console.log('开始心跳检测');
    // 进入程序就进行心跳检测,避免出现开始就连接中断,后续不重连
    // this.heartCheckStart();
    this.calcRunTime();
  }

  /**
   * 发送消息
   * @param message 发送消息
   */
  sendMessage(message) {
   
    this.webSocket.send(message);
  }

  /**
   * 创建新连接
   * @param url 要连接的url
   */
  connect(url) {
   
    if (url) {
   
      this.url = url;
    }
    // 创建websocket对象
    this.createWebSocket();
  }

  /**
   * 创建连接
   */
  createWebSocket() {
   
    console.log('createWebSocket:', this.url);
    // 如果没有建立过连接,才建立连接并且添加时间监听
    this.webSocket = new WebSocket(this.url
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值