uni-app webscoket 连接实例,带心跳检测,断线重连

809 阅读1分钟
  <view>
    <text>WebSocket Heartbeat Example</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      ws: null,
      timeout: null,
      heartbeatMessage: 'ping',
      heartbeatInterval: 5000, // 心跳间隔,单位:毫秒
      reconnectInterval: 1000, // 断线重连间隔,单位:毫秒
      lastHeartbeatTime: null, // 上一次心跳时间
    };
  },
  onShow() {
    this.connect();
  },
  methods: {
    connect() {
      this.ws = uni.connectSocket({
        url: 'ws://echo.websocket.org',
      });
      this.ws.onOpen(() => {
        console.log('WebSocket connected');
        this.startHeartbeat();
      });
      this.ws.onClose(() => {
        console.log('WebSocket disconnected');
        clearTimeout(this.timeout);
        setTimeout(() => {
          this.connect();
        }, this.reconnectInterval);
      });
      this.ws.onError(error => {
        console.error('WebSocket error:', error);
      });
      this.ws.onMessage(res => {
        if (res.data === this.heartbeatMessage) {
          console.log('Received heartbeat:', res.data);
          this.lastHeartbeatTime = new Date().getTime();
        }
      });
    },
    startHeartbeat() {
      this.sendHeartbeat();
      this.timeout = setTimeout(() => {
        this.checkHeartbeat();
      }, this.heartbeatInterval);
    },
    sendHeartbeat() {
      this.ws.send({
        data: this.heartbeatMessage,
      });
    },
    checkHeartbeat() {
      const now = new Date().getTime();
      if (now - this.lastHeartbeatTime > this.heartbeatInterval) {
        console.log('Heartbeat timeout');
        this.ws.close();
      } else {
        this.startHeartbeat();
      }
    },
  },
};
</script>