Introduction
Out of many uses of real time communication using SignalR, chat is one of the important features. Here, I will try to explain the difference between two methods in SignalR to send group messages.
Using the Code
SignalR has two methods:
Clients.All.receiveMessage(msgFrom, msg);
and:
Clients.Group(GroupName,Exceptional).receiveMessage(msgFrom, msg);
(In both methods, receiveMessage(msgFrom, msg)
is a client side method to be called from SignalR Hub server.)
Both methods are useful in group message broadcast. But there is an important difference between these two methods.
The method...
Clients.All.receiveMessage(msgFrom, msg);
...broadcasts the message to all connected users of hub. To send message to limited users, exclude those users, is the option given.
string[] Exceptional = new string[1];Exceptional[0] = connection_id;
Clients.AllExcept(Exceptional).receiveMessage(msgFrom, msg);
To add number of connection ids to an array is a hectic and time consuming work. Hence it is better to use Group messaging in a signalR.
Clients.Group(GroupName,Exceptional).receiveMessage(msgFrom, msg);
It is the right method to broadcast messages to users connected to group. Here also, the option to add, exceptional is available to exclude some users from receiving messages.
Use...
Groups.Add(connection_id, GroupName);
...to add connection id of incoming user to group.
For private chat, rather than excluding all other users than receiver one, simply send the message only to the particular user.
Clients.Client(touserid).receiveMessage(msgFrom, msg);
Here, touserid
is the connection id of user who is going to receive the message.
Please find my article, “SignalR with ASP.NET – One-to-one and Group Chat with Database Record Maintained at Server” for demo application of the same along with explanation.