md-weber / webrtc_tutorial

108 stars 81 forks source link

Auto reconnect when the connection is disconnected or fails #11

Open manishsaxenavidealpha opened 10 months ago

manishsaxenavidealpha commented 10 months ago

thanks, for the great🌟 repo on webRTC in flutter. I

'm working on this for months, and facing some problems. (I'm working on flutter web) 1) Sometimes 2 different systems doesn't connect to each other, sometimes need to hit 3-4 times joinRoom button for connection. 2) Big problem-Sometimes connection establishes after then if it disconnected/ failed to connect in the mid of meeting, there should be a method of reconnectAgain. I tried to reconnect by putting joinRoom method but this approach is wrong or not working. here is the code: ` void registerPeerConnectionListeners() { peerConnection?.onIceGatheringState = (RTCIceGatheringState state) => debugPrint('ICE gathering state changed: $state');

peerConnection?.onConnectionState = (RTCPeerConnectionState state) {
  debugPrint('Connection state change: $state');
  if (state == RTCPeerConnectionState.RTCPeerConnectionStateFailed) {
    debugPrint('it is failed');
    // reconnectIfNeeded();
  } else if (state == RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
    debugPrint('it is connected now');
  } else if (state == RTCPeerConnectionState.RTCPeerConnectionStateDisconnected) {
    debugPrint('it is RTCPeerConnectionStateDisconnected');
    // reconnectIfNeeded();
  }
};

peerConnection?.onSignalingState = (RTCSignalingState state) => debugPrint('Signaling state change: $state');

peerConnection?.onIceGatheringState = (RTCIceGatheringState state) {
  debugPrint('ICE connection state change: $state');
  if (state == RTCIceGatheringState.RTCIceGatheringStateComplete) {
    debugPrint(' RTCIceGatheringState.RTCIceGatheringStateComplete');
  } else if (state == RTCIceGatheringState.RTCIceGatheringStateGathering) {
    debugPrint(' RTCIceGatheringState.RTCIceGatheringStateGathering');
  } else if (state == RTCIceGatheringState.RTCIceGatheringStateNew) {
    debugPrint(' RTCIceGatheringState. RTCIceGatheringStateNew');
  }
};

peerConnection?.onAddStream = (MediaStream stream) {
  debugPrint("Add remote stream");
  onAddRemoteStream?.call(stream);
  remoteStream = stream;
};

}

/////// void reconnectIfNeeded() { if (peerConnection != null && (peerConnection!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateDisconnected || peerConnection!.connectionState == RTCPeerConnectionState.RTCPeerConnectionStateFailed)) { debugPrint('Reconnecting...'); // joinRoom(); this is not working need to add another logic, how can I reconnect again } } ` thanks in advance

aminetoktokmessai commented 4 months ago

Hello, Here is my implementation for reconnecting, tested on android and chrome and does the job for me. Code might seem not optimized enough (not reusing old ice candidates, sdp offers...etc) https://github.com/aminetoktokmessai/webrtc_tutorial/tree/main/lib