react-native - 如何在 React Native 的后台保持套接字连接处于事件状态?

标签 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);

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

最佳答案

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

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

关于react-native - 如何在 React Native 的后台保持套接字连接处于事件状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59983334/

相关文章:

javascript - 一次只显示一个元素与 .map() react

node.js - Socket.io消息的发送者无法像其他用户一样获取消息

reactjs - 可触摸的不透明度标题 React Native

android - 在 android 4.0.3 上 react native 。可能的?

node.js - 使用 socket.io,如何处理非浏览器客户端的身份验证?

javascript - socket.io流错误: stream has already been sent

javascript - 为什么要执行前一个屏幕组件中的 socket.on() ?

c# - 如何断开与 socketio4net 的连接

javascript - 将 React Native 应用程序集成到现有的 iOS Obj-C/Swift 应用程序中

github - 编译ReactAndroid,fbjni错误