(记)在remax,小程序,react hooks中使用实时通信

1.创建一个wxsocket.js

import {
  connectSocket,
  onSocketOpen,
  onSocketClose,
  sendSocketMessage,
  onSocketMessage,
  getNetworkType,
  closeSocket,
  onNetworkStatusChange
} from 'remax/wechat';
class Websocket {
  constructor({ heartCheck, isReconnection }) {
    this.init = false;
    // 是否连接
    this.isConnect = false;
    // 当前网络状态
    this.netWork = true;
    // 是否人为退出
    this.isClosed = false;
    // 心跳检测频率
    this.timeout = 3000;
    this.timeoutObj = null;
    // 当前重连次数
    this.connectNum = 0;
    // 心跳检测和断线重连开关,true为启用,false为关闭
    this.heartCheck = heartCheck;
    this.isReconnection = isReconnection;
    this.wsUrl = "";
    this.onSocketOpened();
  }

  // 心跳重置
  reset () {
    clearTimeout(this.timeoutObj);
    return this;
  }

  // 心跳开始
  start () {
    let self = this;
    this.timeoutObj = setInterval(() => {
      sendSocketMessage({
        // 心跳发送的信息应由前后端商量后决定
        data: JSON.stringify({
          "beat": 'dj'
        }),
        success (res) {
          // console.log(res)
          // console.log("发送心跳成功");
        },
        fail (err) {
          console.log(err);
          // this.reConnect(options)
          console.log('连接失败');
          self.reset();
        }
      }).then();
    }, this.timeout);
  }

  // 监听websocket连接关闭
  onSocketClosed (options) {
    onSocketClose(err => {
      console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
      // 停止心跳连接
      if (this.heartCheck) {
        this.reset();
      }
      // 关闭已登录开关
      this.isConnect = false;
      // 检测是否是用户自己退出小程序
      if (!this.isClosed) {
        // 进行重连
        if (this.isReconnection) {
          this.reConnect(options);
        }
      }
    });
  }

  // 检测网络变化
  onNetworkChange (options) {
    onNetworkStatusChange(res => {
      console.log('当前网络状态:' + res.isConnected);
      if (!this.netWork) {
        this.isConnect = false;
        // 进行重连
        if (this.isReconnection) {
          this.reConnect(options);
        }
      }
    });
  }

  onSocketOpened (callBack) {
    onSocketOpen(res => {
      console.log('websocket已打开');
      // 打开已登录开关
      this.isConnect = true;
      // 发送心跳
      if (this.heartCheck) {
        this.reset().start();
      }
      // 发送登录信息
      sendSocketMessage({
        // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
        data: JSON.stringify({
          "beat": 'dj'
        })
      }).then();
      // 打开网络开关
      this.netWork = true;
      if (typeof callBack == "function") {
        callBack(res);
      }
    });
  }

  // 接收服务器返回的消息
  onReceivedMsg (callBack) {
    onSocketMessage(msg => {
      if (typeof callBack == "function") {
        callBack(msg);
      }
    });
  }

  // 建立websocket连接
  initWebSocket (options) {
    let self = this;
    this.wsUrl = options.url ? options.url : this.wsUrl;
    if (this.isConnect) {
      console.log("您已连接了");
    } else {
      // 检查网络
      getNetworkType({
        success (res) {
          if (res.networkType !== 'none') {
            // 开始建立连接
            connectSocket({
              url: self.wsUrl,
              success (res) {
                if (typeof options.success == "function") {
                  options.success(res);
                }
              },
              fail (err) {
                if (typeof options.fail == "function") {
                  options.fail(err);
                  console.log('连接失败');
                }
              }
            });
          } else {
            console.log('网络已断开');
            self.netWork = false;
          }
        }
      }).then();
    }
  }

  // 发送websocket消息
  sendWebSocketMsg (options) {
    // console.log("send参数:", options)
    sendSocketMessage({
      data: options.data,
      success (res) {
        if (options.success && typeof options.success == "function") {
          options.success(res);
        }
      },
      fail (err) {
        if (options.fail && typeof options.fail == "function") {
          options.fail(err);
        }
      }
    }).then();
  }

  // 重连方法,会根据时间频率越来越慢
  reConnect (options) {
    let timer, self = this;
    if (this.connectNum < 3) {
      timer = setTimeout(() => {
        this.initWebSocket(options);
      }, 3000);
      this.connectNum += 1;
    } else if (this.connectNum < 10) {
      timer = setTimeout(() => {
        this.initWebSocket(options);
      }, 10000);
      this.connectNum += 1;
    } else {
      timer = setTimeout(() => {
        this.initWebSocket(options);
      }, 450000);
      this.connectNum += 1;
    }
  }

  // 关闭websocket连接
  closeWebSocket () {
    closeSocket().then();
    this.isClosed = true;
    this.isConnect = false;
  }
}

const websocket = new Websocket({
  // true代表启用心跳检测和断线重连
  heartCheck: true,
  isReconnection: true
});
export default websocket;

2.使用

import websocket from "../../utils/wxsocket";
  React.useEffect(() => {
    if (token) {
      const wsUrl = process.env.NODE_ENV === 'development' ? `wss://test.onemorecar.cn/ws/notify?token=${token}` : `wss://tt.onemorecar.cn/ws/notify?token=${token}`;
  
      if (!websocket.init) {
        websocket.initWebSocket({ url: wsUrl });
        websocket.onSocketClosed({
          url: wsUrl
        })
        websocket.onNetworkChange({
          url: wsUrl
        })
        websocket.onReceivedMsg(res => {
          console.log('app.js收到服务器内容:' + res.data);
          const { msg, count, status } = JSON.parse(res.data);
          if (count) {
            notify.setNotify(count);
          }
        });
      }
    }
    },[])
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值