Ask Your Question
3

How can a message be sent to all except the person who initiated it using SignalR?

asked 2022-07-08 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-09-01 20:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-07-08 11:00:00 +0000

Seen: 9 times

Last updated: Sep 01 '21