I am using signalR
in my ASP.NET application, I opened the chat view in two different pages noting that I am using groups method. If I start the conversation from one of those two users, the messages doesn't showing up in the other user's page unless he sent one message.
The messages should be prevent once both users have been opened the view, please any way to solve this??
Java Script file:
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
//Disable the send button until connection is established.
document.getElementById("sendButton").disabled = true;
connection.on("ReceiveMessage", function (user, message) {
var li = document.createElement("li");
document.getElementById("messagesList").appendChild(li);
// We can assign user-supplied strings to an element's textContent because it
// is not interpreted as markup. If you're assigning in any other way, you
// should be aware of possible script injection concerns.
li.textContent = `${user} says ${message}`;
});
connection.start().then(function () {
document.getElementById("sendButton").disabled = false;
}).catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
var roomId = document.getElementById("RoomId").value;
connection.invoke("JoinRoom", roomId).catch(function (err) {
return console.error(err.toString());
});
connection.invoke("SendMessage", user, message, roomId).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
Chat Hub:
public async Task SendMessage(string user, string message, string RoomId)
{
//await Clients.All.SendAsync("ReceiveMessage", user, message);
await Clients.Group(RoomId).SendAsync("ReceiveMessage", user, message);
}
public async Task JoinRoom(string RoomId)
{
await Groups.AddToGroupAsync(Context.ConnectionId, RoomId);
}
CodePudding user response:
As our friend mentioned, the previous code was adding the user to the room when he sent a message so I modified the code and added this lines, which mean adding the user to the room as soon the connection has been accomplished.
connection.invoke("JoinRoom", roomId).catch(function (err) {
return console.error(err.toString());
Those lines have been added to the function connection.start()