1

我创建了一个项目 x,但我看不到错误在哪里。一切正常,但私人消息不起作用。下面的链接是我的示例项目。在我的真实项目中,客户端的上下文中有一个名为 connectionToken 的功能。如何获取 connectionToken 值或为什么存在?

**我在我的真实项目中使用Redis背板示例项目链接:https ://github.com/fdevGit/SignalRExample

4

1 回答 1

0

从您提供的代码中,使用Clients.User()not Clients.Client()

Clients.User(...)接受用户标识符。您的参数是 connectionId,这是一个不同的概念,与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);
    }






还有一个关于名称的建议callback method。中返回不同的方法名称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);
    }

char.js 中的相同变化

connection.on("ReceiveMessageToMe", function (user, message) {
    var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    var encodedMsg = user + " says " + msg + " by " + targetConnectionId;
    var li = document.createElement("li");
    li.textContent = encodedMsg;
    document.getElementById("messagesList").appendChild(li);
});

测试截图

在此处输入图像描述

于 2020-08-13T14:07:20.427 回答