I'm working on an ASP.NET MVC app using SignalR that implements a WhatsApp Chat, where the user can send a message from the app to a WhatsApp number, and from there it can be answered, thus showing the response on the page. So far, I've got to separate the messages sent from the WhatsApp account to each tab on different browsers, as I'm using the SignalR connectionID, given that each time a page is loaded, a new connection is established.

From the client, I send the messages as follows

connection.invoke("SendMessage", user, message).catch(function (err) {     return console.error(err.toString()); }); 

and from the server, I send the message to all clients as follows

public async Task SendMessage(string user, string message) {     await Clients.All.SendAsync("ReceiveMessage", user, message); } 

To a particular client, I send a message with the connectionID

await _hubContext.Clients.Client(idConexion).SendAsync("ReceiveMessage", "Message:", textMessage[0].Text.Body);

What I'd like is that the same browser is considered as only one connection, no matter how many tabs are opened. I know from the documentation and other StackOverflow questions that each tab opened is a different connection, but I just need to broadcast the same message to all active tabs of a browser. My current logic is that messages are sent to a particular connection, using the unique WAMID from each message from the WhatsApp Business API.

Tag:asp.net-mvc, signalr

3 comments.

  1. Frank M

    You will want to review putting each user in their own "group". Then instead of sending to the connection, you send to the group.

    This way, no matter how many tabs are open, they will all receive the same message when sent from the hub.

    Group Documentation for Asp.Net SignalR v4.x

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

    Group Documentation for ASP.NET Core

    await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
    1. George1917

      Thanks for your answer, but I don't understand how will it differentiate between tabs on a browser (which have different ID, as it appears that the ID is reset on every request) and tabs on different browsers.

    2. Frank M

      When you add a user to a group and you send something to that group, every member of the group gets the message. It won't matter if they are on multiple tabs, different browsers, different devices. The ID is irrelevant in terms of the connection. SignalR handles sending to the proper members (connection ID) of the group.

Add a new comment.