如何在React Native的后台保持套接字连接的活动状态?

时间:2020-01-30 09:59:28

标签: react-native socket.io

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

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

然后在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);

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

1 个答案:

答案 0 :(得分:2)

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

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

_handleAppStateChange(state) {
    if (state == "background") {
        socket.connect();
    }
}
相关问题