Ask Your Question

Revision history [back]

click to hide/show revision 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.

  1. First, add the SignalR library to your project using NuGet package manager.

  2. 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();
    }
}
  1. Create a method in the hub class that sends messages to all clients except the caller. Use the 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);
}
  1. In the client side, connect to the hub and invoke the Send method with the message data.
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .build();

connection.start().then(function() {
    connection.invoke("Send", "Hello, world!");
});
  1. Finally, define a method in the client that listens to the 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.