Peerjs reconnecting not working fine sometime one of the device is not connected

26 views Asked by At

I creating an video chat application with peerjs, socket (Nodejs) and front end is reactjs application.On join room it works fine but for reconnect it is not working fine. I test it with turning internet off for one device but sometime one of the remote device cannot see reconnected user

Below is my front end reactjs code to reconnect peer connection for video chat application. In which i check if internet is restore check via socket.

 useEffect(() => {
    const recPeerAndJoinRoom = async () => {
      try {
        setRemoteStreams([])
        setPrevPeerId(peer._lastServerId)
        setIsReconnected(true)
        initPeerJsConnection()
      } catch (error) {
        console.log(error)
      }
    }

    if (isSocketConnected) {
      if (roomActive) {
        if (peer.disconnected) {
          console.log('disconnected peer')
          recPeerAndJoinRoom()
        } else {
          joinAndRec()
        }
      }
    }
  }, [isSocketConnected]);


const joinAndRec = async (prevPeerId = null) => {
    const payload = {
      roomId: myRoomId,
      userId: peer.id,
      userName: userName,
      uuId: uuId,
      rejoin: prevPeerId ? false : true,
      prevPeerId: prevPeerId
    }
    await socket.emit('join-room', payload)
    await socket.emit('reconnected-from-client', myRoomId, peer.id)
    setRemoteStreams([])
    userConnected(localStream)
  }

const userConnected = async streamTmp => {
    console.log('socket--->', socket)
    await socket.emit('ready', myRoomId, peer.id)

    /*below on call function will be added to peer events*/
    peer.on('call', call => {
      console.log('call')
      handleIncomingCall(call, streamTmp)
    })

    /*below user-connection function will be added to socket events*/
    socket.on('user-connected', remoteUserId => {
      if (remoteUserId !== null) {
        initiateCall(remoteUserId, streamTmp)
      } else {
        // console.log('User Id is null')
      }
    })

    setLocalStream(streamTmp)
    setRoomActive(true)
  }
  
  const initPeerJsConnection = async () => {
    const PeerJs = (await import('peerjs')).default
    const peerConfig = process.env.NEXT_PUBLIC_NODE_ENV === 'local' ? {} : ICESERVER
    const peerInstance = new PeerJs(peerConfig)

    // Hanldle Connection
    await peerInstance.on('open', userId => {
      setPeer(peerInstance)
    })
    peerInstance.on('error', err => {
      console.log(err)
    })
    peerInstance.on('disconnected', () => {
      // console.log('disconnected', peerInstance)
      // peerInstance.reconnect()
    })
    return peerInstance
  }

Below is my back end nodejs code for ping pong technique and after every 5 seconds i check if pong difference is between 6 to 40 seconds then emit 'connection-lose' to remote screens.

socket.on("pong", (roomId, uuId) => {
      const user = rooms[roomId]?.find((item) => item.uuId === uuId);
      if (user) {
        user["pingAt"] = new Date();
      }
    });

    const pingInterval = setInterval(() => {
      io.to(payload.roomId).emit("ping", payload.roomId);

      setTimeout(() => {
        connectionInterval();
      }, 2000);
    }, 5000); // Send "ping" event every 5 seconds

    // Have to re-write this code
    const connectionInterval = () => {
      const currentTime = new Date().getTime();
      const roomId = payload.roomId;

      rooms[roomId]?.forEach((user) => {
        const timeDifference = currentTime - user.pingAt.getTime();
        if (timeDifference <= 6000) {
          if (user) {
            if (!user["connection"]) {
              user["connection"] = true;
              io.to(roomId).emit(
                "reconnected-from-server-lack",
                user.peerId,
                timeDifference
              );
            }
          }
        } else if (timeDifference > 6000 && timeDifference < 40000) {
          if (user) {
            if (user["connection"]) {
              user["connection"] = false;
              io.to(roomId).emit("connectionLose", user.peerId, timeDifference);
            }
          }
        } else if (timeDifference >= 40000) {
          removeParticipant(socket, roomId, user.peerId, 2);
        }
      });
    };

May be my way is not right please suggest better one also if anybody knows.

0

There are 0 answers