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.
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
Asked: 2022-07-08 11:00:00 +0000
Seen: 9 times
Last updated: Sep 01 '21
What is the process for incorporating std::hash into a class template?
What is the process for adding a class path permanently to the Mac terminal?
How can the __iter__ method of the cursor class in psycopg2 be expanded?
What is the process for obtaining and recording all Linq To Db queries in a database table?
What is the method for directing focus toward the subset within an existing class?
How do I reference media element events located on a ContentView from a ContentPage XAML CS class?
What is the issue when Selenium is unable to locate an element by its class name?
Is there a potential for a conflict between the name of a class and the name of a property?
How to obtain the value of an annotation by using reflection?