Vijay
Vijay

Reputation: 383

Unable to send message to groups in SignalR

I'm using SignalR 2.2.1 in my chat application.

I'm adding users to groups and sending messages to the group. While sending a message, I'm fetching the group name from the user object as follows.

I'm unable to send messages to a group whereas sending messages to the caller or all clients works.

Server-side code:

public string AddUsersToGroup(string CurrentUserId, string toUserId)
{   
    string strGroupName = GetUniqueGroupName(CurrentUserId, toUserId);
    if (!string.IsNullOrEmpty(toUserId) && !string.IsNullOrEmpty(CurrentUserId))
    {
        string _cnId, _toCnId;
        _cnId = UsersOnline.userObj.Where(item => item.userId == CurrentUserId).Select(item => item.ConnectionIds.FirstOrDefault()).FirstOrDefault();
        _toCnId = UsersOnline.userObj.Where(item => item.userId == toUserId).Select(item => item.ConnectionIds.FirstOrDefault()).FirstOrDefault();
        UsersOnline.userObj.Where(item => item.userId == CurrentUserId).FirstOrDefault().GroupName = strGroupName;
        UsersOnline.userObj.Where(item => item.userId == toUserId).FirstOrDefault().GroupName = strGroupName;

        Groups.Add(_cnId, strGroupName);
        Groups.Add(_toCnId, strGroupName);                               
    }
    return strGroupName;
}

public void Send(string message)
{
    if (Clients != null)
    {
        string _conId = Context.ConnectionId;
        string GroupName = UsersOnline.userObj.Where(item =>   item.ConnectionIds.Contains(_conId)).FirstOrDefault().GroupName;
        Clients.Group(GroupName).broadcastMessage(message); // This doesn't work.
        Clients.All.broadcastMessage(message); // This works.
        Clients.Caller.broadcastmessage(message); // This works.
    }
}

private string GetUniqueGroupName(string CurrentUserId, string toUserId)
{
    return (CurrentUserId.GetHashCode() ^ toUserId.GetHashCode()).ToString();
}

Client side code:

chat.client.broadcastMessage = function (message) {              
    $('#divMessageBoard').append('<span>' + $('<div/>').text(message).html() + '</span><br/>');
    var divMessageBoard = $('#divMessageBoard');
    $("#divMessageBoard").animate({ scrollTop: $("#divMessageBoard")[0].scrollHeight }, 1000);
};

Can anyone please suggest a solution?

Thanks.

Upvotes: 0

Views: 233

Answers (1)

Kelso Sharp
Kelso Sharp

Reputation: 972

Don't use gethashcode to generate the name of the group, the results will only match if all the data for the user is identical, and if there is a disconnect, or the connectionid change the group name will no longer be valid for that user. You can use ConnectionId since it is unique for each user. Also Pawel is correct you are creating the groups but you are not adding the user to the group itself.

Upvotes: 0

Related Questions