0
votes

I have an asp.net mvc 4 app that uses SignalR.

When an user is connected I want to notify everyone of that (sending to "all" for the moment just to test it). In my Hub clas I have this:

    public override System.Threading.Tasks.Task OnConnected()
    {
        NotifyAllOfUserLogin(); 
        return base.OnConnected();
    }

In the _layout.cshtml, I have this:

        <script type="text/javascript">
        $(document).ready(function () {
            var proxy = $.connection.messagehub;

            proxy.client.messageAll = function (message) {
                $('#messages').prepend('<p style=\'white-space:pre;\'>' + message + '</p><br />'); 
            };

            $("#btnSubmitMessage").click(function () {
                proxy.server.messageAll($("#txtMessage").val());
                $("#txtMessage").val('');
            });

            $.connection.hub.start();
        });
    </script>

While this works, I think writing this in the masterpage is a mistake, since the hub connection will be reinitialized for every page that inherits the master, so OnConnected will be called a lot of times.

How should I deal with this properly, calling OnConnect only when the user logs into the application, and onDisconnected when the user logs out?

1

1 Answers

3
votes

For every page-load, a new connection is made. When that page is closed, similarly that specific connection is closed.

What you will want to do is keep track of the user's connection ID's on the server-side. You will need to keep track of the active connections related to each specific user account, and also when they disconnect. Doing so, you can notify all users that a person connected if there are no pre-existing active connection ID's related to that user.