2

I have a basic MVC application which is integrated with signal R. I'm tracking online users using this application.

Following is my Hub class

public class UserHub : Hub { static long counter = 0;

public override Task OnConnected()
{
    //Update Count when User is connected
    counter = counter+1;
    Clients.All.UpdateCount(counter);
    return base.OnConnected();
}

public override Task OnDisconnected(bool stopCalled)
{

    counter = counter-1;
    Clients.All.UpdateCount(counter);
    return base.OnDisconnected(stopCalled);

}

}

Following is my javascript code

        $.connection.hub.logging = true;
        //setup hubs
        var userHub = $.connection.userHub;
        $.connection.hub.start().done(function () {

        });

        //function to recieve data from server
        userHub.client.UpdateCount = function (count) {
            $('#counter').text(count);
        }

I have registered the in startup.cs class as well.

The problem is signalr Is throwing an error "SignalR: No hubs have been subscribed to. " When I refresh the page like 5 times, then the signal r is connected to hub and data is getting pulled.

Did anyone face this issue?

Any help is appreciated.

Thank you

ISHIDA
  • 4,700
  • 2
  • 16
  • 30

2 Answers2

6

Start the connection after you're subscribing to the client method, like so:

var cHub = $.connection.userHub;
cHub.client.UpdateCount = function (count) {
    $('#counter').text(count);
}

$.connection.hub.start();
Ofir
  • 517
  • 4
  • 16
  • I tried this, this happens to work. Can you tell me the reason behind it ? – ISHIDA Oct 29 '17 at 12:40
  • 2
    Take a look in here: https://stackoverflow.com/questions/16064651/the-on-event-on-the-signalr-client-hub-does-not-get-called basically, signalR subscribe to the hub client callbacks on start so you have to define it before. – Ofir Oct 29 '17 at 14:05
0

I was able to resolve the issue by setting a timeout. Following is my code.

var cHub = $.connection.userHub;
            setTimeout(function () {
                $.connection.hub.start();
            },
                1000);
            //function to recieve data from server
            cHub.client.UpdateCount = function (count) {
                $('#counter').text(count);
            }

            $.connection.hub.logging = true;

I still was not able to figure out why the firefox is doing that.

ISHIDA
  • 4,700
  • 2
  • 16
  • 30