Search code examples
javascriptasp.net-coresignalr

connection.disconnected is not a function


I am confused :)

I am using SignalR with Asp.Net Core with a JavaScript client. I just want to detect a disconnect and reconnect automatically.

After much Googling I came up with this:

connection.disconnected(function() {
   setTimeout(function() {
       $.connection.hub.start();
   }, 5000); // Restart connection after 5 seconds.
});

But I get the error:

connection.disconnected is not a function

This is my entire JavaScript Client:

 $(document).ready(function () {

    var divTimeStamp = document.getElementById("divTimeStamp");
    var img = document.getElementById('imgTest');
    var connection = new signalR.HubConnectionBuilder().withUrl("/NotificationUserHub").build();

    //Disable send button until connection is established
    document.getElementById("sendButton").disabled = true;

    connection.on("ReceiveMessage", function (user, image,timestamp ) {
        try {
            img.src = 'data:image/png;base64,' + image;
            divTimeStamp.innerText = timestamp;
        } catch (error) {
            console.error(error.toString());
        }
    });

   connection.disconnected(function() {
       setTimeout(function() {
           connection.start();
       }, 5000); // Restart connection after 5 seconds.
   });

    document.getElementById("sendButton").addEventListener("click", function (event) {
        var user = document.getElementById("userInput").value;
        var message = document.getElementById("messageInput").value;
        connection.invoke("MessageFromClient", user, message).catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
});

Changing to this:

function connection.disconnected(function () {

gives this:

enter image description here

I also tried this:

connection.on("disconnect", function() { 
    setTimeout(function() { 
       connection.start(); 
 }, 5000); // Restart connection after 5 seconds. }); 

connection.on("disconnected", function() { 
    setTimeout(function() { 
       connection.start(); 
}, 5000); // Restart connection after 5 seconds. 

Solution

  • How about using the approch recommanded by microsoft

    async function start() {
        try {
            await connection.start();
            console.log("connected");
        } catch (err) {
            console.log(err);
            setTimeout(() => start(), 5000);
        }
    };
    
    connection.onclose(async () => {
        await start();
    });
    

    reference : https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.2