【问题标题】:How can I keep a socket connection alive in the background in React Native?如何在 React Native 的后台保持套接字连接处于活动状态?
【发布时间】:2020-01-30 09:59:28
【问题描述】:

我使用 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);

在真机中,当应用程序进入后台时,一段时间后socket会断开,我无法重新连接,如何保持连接?

【问题讨论】:

    标签: react-native socket.io


    【解决方案1】:

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

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

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

    【讨论】:

    • 我认为当应用程序被滑动关闭/杀死时这将不起作用
    • @RakibUddin,此解决方案仅适用于应用程序进入后台。如果它杀了,那又是另一段历史了,对吧?
    • 如果我关闭应用然后服务器发出一些东西,那么关闭的应用就会崩溃。
    猜你喜欢
    • 2018-04-13
    • 2012-07-08
    • 2014-08-19
    • 2011-09-07
    • 1970-01-01
    • 2021-07-31
    • 2013-09-23
    • 1970-01-01
    相关资源
    最近更新 更多