Skip to content

Sip.js Reconnection Issue when Web socket connection Lost or Network connectin lost #1095

Open

Description

@m-yunus

I am facing an issue with reconnection handling in SIP.js when the WebSocket connection is lost or the network is disconnected. After a disconnection, the onDisconnect delegate is triggered, but the UserAgent doesn't reconnect properly, and I can't maintain registration automatically.
const transportOptions = {
server: "wss:///ws",
traceSip: true,
iceCheckingTimeout: 35000,
register: true,
stunServers: ["stun:stun.l.google.com:19302"],
turnServers: [
{
urls: "t",
username: "",
credential: "",
},
],
connectionTimeout: 5,
maxReconnectionAttempts : 100,
reconnectionTimeout: 4,
keepAliveInterval: 10
};
const handleRegister = (event) => {
const uri = UserAgent.makeURI(sip:${sipUri}@);
const userAgentOptions = {
authorizationUsername: sipUri,
authorizationPassword: "",
transportOptions,
uri,
delegate: {
onInvite,
onDisconnect: (error) => {
alert("disconnected")
console.log("Network connectivity lost");
if (!error) {
console.log("User agent stopped");
}
},
onConnect: () => {
alert("connected")
handleRegister();
console.log("Network connectivity established");
},

}

};

const ua = new UserAgent(userAgentOptions);
setUserAgent(ua);

ua.start()
.then(() => {
const registerer = new Registerer(ua);
return registerer.register({
requestDelegate: {
onAccept(response) {
isRegistering = false;
alert("registerred successfully")
console.log("UserAgent registered successfully", response);
},
onReject(sip) {
isRegistering = false; // Reset flag on failure
console.log("UserAgent registration failed", sip);

    },
  },
});

})
.catch((error) => {
isRegistering = false;
console.error("Error starting the UserAgent:", error);
});
} I’ve reviewed the SIP.js documentation and attempted to use the onDisconnect and onConnect delegates for handling reconnections, but I'm unable to achieve reliable re-registration.

Any guidance or recommendations would be greatly appreciated.

Activity

  1. greatapps commented on Dec 14, 2024

    @greatapps

    Is there any solution on this, How to handle the same ?

  2. shibran commented on Jan 30, 2025

    @shibran

    You have to call reconnection method inside onDisconnect delegate. Like,

    const reconnectionAttempts = 3;
    const reconnectionDelay = 4;
    let attemptingReconnection = false;
    let shouldBeConnected = true;
    
    userAgent.delegate.onDisconnect = (error) => {
      if (error) {
        attemptReconnection();
      }
    };
    
    const attemptReconnection = (reconnectionAttempt = 1)=> {
      // If not intentionally connected, don't reconnect.
      if (!shouldBeConnected) {
        return;
      }
    
      // Reconnection attempt already in progress
      if (attemptingReconnection) {
        return;
      }
    
      // Reconnection maximum attempts reached
      if (reconnectionAttempt > reconnectionAttempts) {
        return;
      }
    
      // We're attempting a reconnection
      attemptingReconnection = true;
    
      setTimeout(() => {
        // If not intentionally connected, don't reconnect.
        if (!shouldBeConnected) {
          attemptingReconnection = false;
          return;
        }
        // Attempt reconnect
        userAgent.reconnect()
          .then(() => {
            // Reconnect attempt succeeded
            attemptingReconnection = false;
          })
          .catch((error) => {
            // Reconnect attempt failed
            attemptingReconnection = false;
            attemptReconnection(++reconnectionAttempt);
          });
      }, reconnectionAttempt === 1 ? 0 : reconnectionDelay * 1000);
    };
    
  3. m-yunus commented on Feb 5, 2025

    @m-yunus
    Author

    i dont hear anything on when an outgoing call not hearting early media any issue on this

  4. jayparmarmagic commented on Jul 16, 2025

    @jayparmarmagic

    After network reconnection (e.g., switching from Wi-Fi to mobile data), the WebSocket and SIP session reconnect successfully. However, even though the call continues and ICE renegotiation completes without errors, audio is not heard on either side post-reconnection.

  5. MadEddieFFS commented on Jul 23, 2025

    @MadEddieFFS

    I have the same issue - It seems that the local web RTC connection remains in place when the connection is lost and then recovered. There should be a renegotiation or some kind of web RTC rebuild to hook up the session after the reinvite.

  6. sravanpurumala commented on Dec 22, 2025

    @sravanpurumala

    After the WebSocket connection is restored, we should restart ICE on both ends. For the remote end, send a re-invite with new ICE parameters in onConnect. After calling userAgent.reconnect in onDisconnect, restart ICE on the RTCPeerConnection as follows:
    userAgent.delegate = {
    onConnect: async () => {
    console.log("Transport connected");
    registerer.register().catch((e) => { console.log(Exception while registering: ${e}); });
    // Re-invite after network switch
    if (invitation && invitation.state !== SIP.SessionState.Terminated) {
    await invitation.invite({
    sessionDescriptionHandlerOptions: {
    offerOptions: {
    iceRestart: true
    }
    }
    });
    }
    },
    onDisconnect: (error) => {
    console.log("UA disconnected: " + error);
    registerer.unregister().catch(() => {
    console.log("Unregister failed");
    });
    // Attempt to reconnect only if network/server dropped the connection
    if (error) {
    attemptReconnection();
    }
    },
    onInvite: async (incomingInvitation) => {
    console.log("Incoming call");
    //...
    }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions