Search code examples
asp.netmodel-view-controllersignalrchatmessage

With SignalR, is it possible to send only one person or group message?


Many sites, including MSDN, have exemplified sending messages to all clients.

For example; With Clients.All.addNewMessageToPage (), the message goes to all users.

What should be done if I just want to send a message to a group of people who are chatting?

Or to send a message to a single contact ...

Thank you...


Solution

  • yes you can send to group of people by joining group like this

    public class ContosoChatHub : Hub
    {
        public Task JoinRoom(string roomName)
        {
            return Groups.Add(Context.ConnectionId, roomName);
        }
    
        public Task LeaveRoom(string roomName)
        {
            return Groups.Remove(Context.ConnectionId, roomName);
        }
    }
    

    and send message to this group by

    Clients.Group(groupName).addChatMessage(name, message);
    

    you can check this link for more info https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/working-with-groups