【问题标题】:Too many connectivity problems in socket in react native with nestjs套接字中的太多连接问题与nestjs反应本机
【发布时间】:2021-09-22 02:48:11
【问题描述】:

我正在使用nestjsreact-nativesocket.io

nestjs 的套接字版本是 "socket.io": "^2.4.1"react-native 使用版本 "socket.io-client": "^2.4.0",

问题在于,大概是在将组件挂载到react-native 后,每次渲染组件时,与套接字服务器(nestjs)的连接太多。 此问题连接有助于降低服务器的速度...

这就是服务器日志的样子。

我已经尝试了很多方法来解决这个问题,但我还没有解决它。

react-native 这是一个帮助我连接的代码。

 const socket = useRef<SocketIOClient.Socket>(io(`${httpUrl}`, { transports :  ['websocket'], query  : { device : Platform.OS }}));
    useEffect(()=>{
        socket.current?.connect()
    },[])

nest.js 这是一个帮助我连接的代码。

@WebSocketGateway( { transports: ['websocket','polling'] })
export class ChatGateWay implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
    public handleConnection(client: Socket) {
          const query = this.getClientQuery(client);

          const remoteAddress = client.conn.remoteAddress

          if(!query.device){

              client.disconnect(true)

              ChatGateway.logger.debug(` DISCONNECTED === ${query.device} and ${remoteAddress} is connected!`);
            } else {

              ChatGateway.logger.debug(`${query.device} and ${remoteAddress} is 
              connected!`);

            }
      return true;
    }


}

您有解决这些问题的方法吗?

【问题讨论】:

标签: reactjs react-native sockets nestjs


【解决方案1】:

我通过将类组件配置为提供者,然后将使用套接字的组件添加到它来解决问题。

解决了这个问题,

class example extends Components {
   ...
   componentDidMount(){
      socket.connected()
   }
   componentWillUnmount(){
      socket.disconnected()  
   }
   render(){
      return <Chidren socket={socekt}/>
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多