How to save connection when u change page in signalR

926 views Asked by At

I've a problem to save connection while I'm changing page. I've one page where show a list of rooms and second page with view of chat. When I'm join page with list of room it join method on connect, after when I'm choosed which room to join, it goes to ondisconnected then JoinGroups then Onconnect method. Tell me please how to make one connection to both pages?

Here the javascript of chathub:

$(function () {

    // Declare a proxy to reference the hub. 
    var chatHub = $.connection.ChatHub;

    registerClientMethods(chatHub);

    // Start Hub
    $.connection.hub.start().done(function () {
        roomsEvent(chatHub);

        authorize(chatHub);

        registerEvents(chatHub);

    });

});

function authorize(hub) {
    var name = $('#txtMessage').prop('Placeholder');
    hub.server.connect(name);
    $('#displayname').val(name);
    messageClearFocus();
    $('#txtMessage').prop('placeholder', '');
}

function roomsEvent(hub) {
    $('#rooms ul li').not('.nav-header').click(function () {

        $('#rooms ul li').not('.nav-header').removeClass('active');
        $(this).addClass('active');
        var roomKey = $(this).data('value');
        hub.server.joinGroup(roomKey);
    });
}

And Connect method:

public void Connect(string userName)
        {
            userName = Context.User.Identity.Name;
            if (ConnectedUsers.Any(x => x.ConnectionId == Context.ConnectionId))
                return;

            //Add a new user to the list
            var user = new ChatUser
            {
                ConnectionId = Context.ConnectionId,
                userLogin = userName
            };

            //Add to maintained user list
            ConnectedUsers.Add(user);

            //Add to default group
            //await 
            Groups.Add(user.ConnectionId, user.CurrentGroup);

            //Give the current group an updated list of users
            UpdateGroupUserList(user.CurrentGroup);

            //Alert others that user joined
            var message = string.Format("{0} has joined.", user.userLogin);
            SendGroupAlert(user, message);

            //Alert user that they have joined
            var personalMessage = string.Format("You have joined {0} as {1}.", user.CurrentGroup, user.userLogin);
            SendPersonalAlert(personalMessage);
        }
1

There are 1 answers

0
user3037172 On BEST ANSWER

It is not possible if they have to switch pages to maintain a connection. What you can do is put it all under one page. See here