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.
I am working as an application developer for last ten years. I am mostly develop applications in ASP.NET. But, also I work in Android and Java.
Currently I am working in a company as a Sr. Application Developer. I have a team of developers and I am playing a role of team leader.
Also, I assist academic projects based on IEEE papers for ME for last ten years.
I believed on a logic development and not on a programming language. I think that, if some one was strong in logic development then he/she can easily develop an application in any programming language.
I am working on tools/domains like, image processing, networking, cloud computing, etc. Out of them, cloud computing is my favorite working domain.