当本机应用程序在后台/设备处于锁定状态时,如何防止socket.io断开连接?

问题描述

标题所示,当我的设备处于锁定屏幕或背景时,我的套接字服务器将确定我的本机应用程序“死”。

有哪些解决方案?

解决方法

在线阅读后,套接字服务器将我的本机应用确定为“死”的原因是,当设备锁定或处于后台时,应用内的所有javascript代码均已停止工作。

因此,我找到了解决此问题的解决方案。

我使用过的工具:

  1. React Native Appstate
  2. React Native Background Timer

我的客户端代码:

io.on('connection',(socket)=>{
  socket.on('online',()=>{
    //do nothing
  })
}
)

我的服务器端代码:

<my-component>
    <div style="color: green;">{{ $parent.$ctrl.variable }}</div>
</my-component>
<my-component>
    <div style="color: red;">{{ $parent.$ctrl.variable }}</div>
</my-component>

此解决方案适用于我的应用。现在,在我关闭应用程序或单击断开连接按钮之前,套接字将不会断开连接。

,

尽管Jin Tan的回答对我有用,并且我的套接字连接保持稳定,但我在套接字连接上使用的进程已关闭(react-native-webrtc)。

我使用了ForegroundService库来保持套接字以及webrtc传输均处于活动状态。组合的代码如下:

import VIForegroundService from '@voximplant/react-native-foreground-service';
import BackgroundTimer from 'react-native-background-timer';

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
      // clearInterval when the app comes back to the foreground
      BackgroundTimer.clearInterval(interval)
    }else{
      // app goes to background
      console.log('app goes to background')
      // tell server that the app is still online when app goes to background
      interval = BackgroundTimer.setInterval(()=>{
        console.log('connection status ',socket.connected)
        this.socket.emit('online')
      },5000)
      this.setState({appState: nextAppState});
      console.log("AppState",this.state.appState);
    }
  }

  async configureForeground(){
    if (Platform.Version >= 26) {
      const channelConfig = {
        id: 'CallNotification',name: `Active Call Notification`,description: 'Active calls will be shown using this notification',enableVibration: false,importance: 1
      };
      await VIForegroundService.createNotificationChannel(channelConfig);
    }
    const notificationConfig = {
      id: 3456,title: 'title',text: 'text',icon: 'ic_notification',priority: 1
    };
    if (Platform.Version >= 26) {
      notificationConfig.channelId = 'voiceCallNotification';
    }
    await VIForegroundService.startService(notificationConfig);
  }

ic_notification是所有mipmap-xxxx文件夹中的图像“ ic_notification.png”。

您可以调用configureForeground()启动通知。 要在componentWillUnmount中终止前台服务:

    AppState.removeEventListener('change',this._handleAppStateChange);
    try{
      VIForegroundService.stopService();
    }catch(err){
      // do nothing if service was never started.
    }