如何在 React Native 的后台保持套接字连接处于活动状态? [英] How can I keep a socket connection alive in the background in React Native?

查看:60
本文介绍了如何在 React Native 的后台保持套接字连接处于活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Wix 导航 v2、socket.io-client、react-native-background-time 和 react-native v59.10首先我在 index.js 中注册一个 HeadlessTask

I use Wix navigation v2, socket.io-client, react-native-background-time and react-native v59.10 first I register a HeadlessTask in index.js

if (Platform.OS === 'android') {
  AppRegistry.registerHeadlessTask(
    'backgroundTask',
    () => backgroundTask
  );
}

然后在 backgroundTask.js 中

then in backgroundTask.js

import BackgroundTimer from 'react-native-background-timer';
import io from 'socket.io-client';

import { showLocalPushNotification } from 'helper/PushNotificationServices';

const URL = 'http://SOME_SECURE_URL'; //:)
const currentTimestamp = () => {
  const d = new Date();
  const z = n => (n.toString().length == 1 ? `0${n}` : n); // Zero pad
  return `${d.getFullYear()}-${z(d.getMonth() + 1)}-${z(d.getDate())} ${z(
    d.getHours()
  )}:${z(d.getMinutes())}`;
};
let socket = io(URL, {
  reconnection: true,
  reconnectionDelay: 1000,
  reconnectionDelayMax: 5000,
  reconnectionAttempts: Infinity,
  autoConnect: true
});
socket.on('connect', () => {
  showLocalPushNotification('Socket Say', `socket connect successfully`);
});

socket.on('disconnect', reason => {
  console.log(reason);
  socket.connect();

  if (reason === 'io server disconnect') {
    // the disconnection was initiated by the server, you need to reconnect manually
  }
  console.log('disconnect');
  showLocalPushNotification('Socket Say', `socket disconnect :(`);
});

socket = socket.on('receive', async data => {
  console.log('receive');
  showLocalPushNotification(
    'Socket Say',
    `${currentTimestamp()}`
  );
  console.log(data);
});

socket.on('reconnect', attemptNumber => {
  console.log('reconnect');

  console.log(attemptNumber);
  // ...
});
socket.on('reconnect_error', error => {
  console.log('reconnect_error');

  console.log(error);
  // ...
});

socket.on('reconnect_failed', () => {
  console.log('reconnect_failed');
  // ...
});

BackgroundTimer.runBackgroundTimer(() => {
  showLocalPushNotification(
    'BackgroundTimer Say',
    `${value || ''}\n${currentTimestamp()}`
  );
  socket.emit('send', { my: 'ok i get news' });

  // this.socket.emit('send', { my: 'ok i get news' });
}, 1000 * 15 * 60);

在真实设备中,当应用程序进入后台时,套接字会在一段时间后断开连接,我无法再次重新连接,如何保持连接?

in a real device, when the app goes to background, the socket will be disconnected after a while and I can't reconnect it again, how can I keep the connection alive?

推荐答案

我长期面临同样的问题,但我解决了在后台发送应用程序时调用 socket.connect() 的问题

I'm facing the same issue for long time, but I solved calling socket.connect() when I send app in background

AppState.addEventListener("change", this._handleAppStateChange.bind(this))

_handleAppStateChange(state) {
    if (state == "background") {
        socket.connect();
    }
}

这篇关于如何在 React Native 的后台保持套接字连接处于活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆