Chat web application using SignalR.
Please make sure to install one of the following
- SignalR service
services.AddSignalR();- Adding new Hub in the startup.cs file
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHub<ChatHub>("/chathub");
});- Hub Method example
public async Task SendMessage(string user, string message)
{
HashSet<string> connectedUsers = new HashSet<string>();
string key = user;
foreach (var connectionId in connections.GetConnections(key))
{
connectedUsers.Add(connectionId);
}
// Send Messages to all users
await Clients.All.SendAsync("ReceiveMessage", user, message);
// Send messages to specific users
// await Clients.Clients(connectedUsers.ToList()).SendAsync("ReceiveMessage", user, message);
}-
Install SignalR js lib SignalR Core client installation
-
Start Connection
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();- Call method
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});- Receive method
connection.on("ReceiveMessage", function (user, message) {
// your code here ...
});