I created a project x and I can't see where the error is. Everything works but the private message doesn't work. The link below is my sample project. In my real project, there is a feature called connectionToken in context on the client. How can I get the connectionToken value or why is it there?
**I use Redis backplane in my real project Example project link: https://github.com/fdevGit/SignalRExample
From the code you provide, use Clients.User()
not Clients.Client()
.
Clients.User(...)
takes a user identifier. Your parameter is connectionId which is a different concept and used with Clients.Client(...)
.
public async Task SendMessageToUser(string user, string targetConnectionId, string message)
{
Console.WriteLine($"{Context.ConnectionId}-{targetConnectionId}-{message}");
//await Clients.User(...)
await Clients.Client(targetConnectionId).SendAsync("ReceiveMessageToUser", user, targetConnectionId, message);
}
There is one more suggestion about the name of callback method
. Return different method name in SendAsync()
.
public async Task SendMessageToMe(string user, string message)
{
Console.WriteLine($"{Context.ConnectionId}-Caller-{message}");
await Clients.Caller.SendAsync("ReceiveMessageToMe", user, message);
}
public async Task SendMessageToUser(string user, string targetConnectionId, string message)
{
Console.WriteLine($"{Context.ConnectionId}-{targetConnectionId}-{message}");
await Clients.Client(targetConnectionId).SendAsync("ReceiveMessageToUser", user, targetConnectionId, message);
}
Same change in char.js
connection.on("ReceiveMessageToMe", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
connection.on("ReceiveMessageToUser", function (user, targetConnectionId, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var encodedMsg = user + " says " + msg + " by " + targetConnectionId;
var li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
Screenshots of Test