How can I keep a socket connection alive in the background in React Native?

倾然丶 夕夏残阳落幕 提交于 2020-04-14 08:39:06

问题


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
  );
}

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?

来源:https://stackoverflow.com/questions/59983334/how-can-i-keep-a-socket-connection-alive-in-the-background-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!