1 | initial version |
One way to send a message to all except the person who initiated it using SignalR is to use the Clients
property of the Hub
class.
First, add the SignalR library to your project using NuGet package manager.
Create a hub class that inherits from Hub
and override the OnConnectedAsync
method to keep track of the connected clients.
public class ChatHub : Hub
{
private static readonly HashSet<string> Users = new HashSet<string>();
public override Task OnConnectedAsync()
{
Users.Add(Context.ConnectionId);
return base.OnConnectedAsync();
}
}
Clients.AllExcept
method with the Context.ConnectionId
parameter to exclude the caller from the message.public void Send(string message)
{
Clients.AllExcept(Context.ConnectionId).SendAsync("ReceiveMessage", message);
}
Send
method with the message data.var connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.start().then(function() {
connection.invoke("Send", "Hello, world!");
});
ReceiveMessage
event and displays the message.connection.on("ReceiveMessage", function(message) {
console.log(message);
});
With these steps, when a client invokes the Send
method, the message will be sent to all other connected clients except the caller.