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

Jin*_*Tan 6 socket.io react-native

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

这些有什么解决办法?

Jin*_*Tan 9

在网上做了一些阅读之后,我的套接字服务器将确定我的 React Native 应用程序“死”的原因是因为当我的设备被锁定或在后台时,我的应用程序中的所有 javascript 代码都停止工作。

因此,我想出了一个解决方案来解决这个问题。

我用过的工具:

  1. 反应本机应用程序状态
  2. 反应本机后台计时器

我的客户端代码:

import React, {useEffect, useRef} from 'react';
import {AppState} from 'react-native'

export default () => {
  const appState = useRef(AppState.currentState);
  var interval

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

useEffect (() => {
    AppState.addEventListener("change", _handleAppStateChange);

    return () => {
      AppState.removeEventListener("change", _handleAppStateChange);
    };
},[])



}


Run Code Online (Sandbox Code Playgroud)

我的服务器端代码:

io.on('connection',(socket)=>{
  socket.on('online',()=>{
    //do nothing
  })
}
)
Run Code Online (Sandbox Code Playgroud)

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