SignalR-未调用客户端功能

时间:2018-09-19 15:59:45

标签: c# signalr

我有两个集线器,如下所示:

ChatHub和AdminHub

我正在使用Javascript存储2个http cookie:一个是用于connectionId的连接ID,在没有cookie的情况下表示rommName,另一个是用于我需要的名称。

在客户端,我有:

//reference the auto generated proxy for the hub
    chat = $.connection.chatHub;
    $.connection.chatHub.logging = true;
    $.connection.chatHub.client.addMessageToPage = onAddMessageToPage;
    $.connection.chatHub.client.addAdminMessageToPage = 
                      onAddAdminMessageToPage;

function onAddMessageToPage(message) {
        chatMessages.append('<div class="chat__message chat__message--outgoing"><div class="chat__text">' + message + '</div></div>');
        chatMessages.animate({ scrollTop: chatMessages.prop('scrollHeight') });
        console.log('addMessageToPage');
    }
    function onAddAdminMessageToPage(message) {
        chatMessages.append('<div class="chat__message chat__message--incoming"><div class="chat__user-icon"></div><div class="chat__username">Admin</div><div class="chat__text">' + message + '</div>');
        chatMessages.animate({ scrollTop: chatMessages.prop('scrollHeight') });
        $('.notification-sound')[0].play();
        if (!chatMessageContainer.is(':visible')) {
            showAnimate(chatMessageContainer);
            hideAnimate(fullNameContainer);
            console.log('addAdminMessageToPage');
        }
    }

if (!readCookie("connectionId")) {
        $.connection.hub.start()
            .done(function () {
                createCookie("connectionId", $.connection.hub.id, 7);
                createCookie("name", "test", 5);
                chat.server.subscribeToClients("test");
                chat.server.sendMessage("test", "message test!");
                console.log('from greenbuttonclick1');

            })
            .fail(function () {
                console.log('error occured!');
            });
    }
    else
        if (readCookie("name") && readCookie("connectionId")) {
            //  I re-added this to make sure that at least this function is 
            //  being registered but no hope!
            chat.client.addMessageToPage = onAddMessageToPage;
            $.connection.hub.start()
                .done(function () {
                    chat.server.subscribeToClients("test");
                    chat.server.sendMessage("test", "message test!");
                })
                .fail(function () {
                    console.log('error occured!');
                });
        }


function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}


function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

在ChatHub的服务器端:

public void SendMessage(string name, string message)
    {
        var cookie = Context.Request.Cookies.SingleOrDefault(c => c.Key == "connectionId");
        string roomName;

        if (cookie.Value == null)
        {
            roomName = Context.ConnectionId;
        }
        else
        {
            roomName = cookie.Value.Value;
        }
        getAnonymousClient(roomName)
                .Messages.Add(new ChatMessage
                {
                    Message = message,
                    MessageDate = DateTime.Now,
                    MessageType = ChatMessageType.ClientMessage
                });
// call the addMessageToPage method on the client
        Clients.Group(roomName).addMessageToPage(message);
        _adminContext.Clients.Group("Admin").addIncomingMessage(roomName,name,message);
        _adminContext.Clients.Group("Admin").checkPendingState(roomName);

    }

在我的情况下,我必须使用cookie来实现连接ID的1:m关系,并且一切运行正确,方法addMessageToPage可以正确触发,但仅是第一次!!!

尽管将邮件发送给管理员,但刷新页面后,addMessageToPage和addIncomingMessage客户端方法都不会触发!

如果有人能给我一个提示,我将非常感激。

更新

我尝试了相同的逻辑,但是使用本地存储来代替,将唯一的GUID作为roomName存储为可处理多个connectionId的roomName,但这一次根本没有调用客户端方法!

当我使用Cookie时,该方法对于页面的第一次访问非常有效,而对于第二次访问则没有效果。

function getRoomName() {
        var roomName = localStorage.getItem('roomName');
        if (!roomName) {
            roomName = Math.uuid();
            localStorage.setItem('roomName', roomName);
        }
        return roomName;
    }

    var roomName = getRoomName();
    var name = localStorage.getItem('name');
    $.connection.hub.qs = { 'roomName' : roomName };
    $.connection.hub.start()
        .done(function () {
            console.log('connected');
            if (name) {
                if (name.length > 0) {
                    chat.server.subscribeToClients(fullNameInput.val());
                    //test server method call
                    chat.server.sendMessage("xxx", "yyy");
                    fullNameInput.val(name);
                    showAnimate(chatMessageContainer);
                    chatHeaderForName.html(fullNameInput.val());
                    chatMessageInput.focus();
                    console.log('name exists & has subscribed');
                }
            }
            chat.server.sendMessage("xxx", "yyy");

        });




 //send message
sendMessageIcon.click(function (e) {
    e.preventDefault();
    chat.server.sendMessage(fullNameInput.val(), chatMessageInput.val());
    chatMessageInput.val('');
    chatMessageInput.focus();
    chatMessages.animate({ scrollTop: chatMessages.prop('scrollHeight') });
});

谢谢

0 个答案:

没有答案