如何使用 SignalR 向特定用户发送数据?

leo*_*ess 7 javascript azure signalr

我有一个通过 SignalR 接收消息的客户端。它运行良好,但更像是广播。我希望能够向特定客户端发送消息。在客户端,我有一个 userId,我像这样设置了我的连接:

const userId = getUserId();

if (userId) {
    const beacon = new signalR.HubConnectionBuilder()
        .withUrl(`${URL}/api?userId=${userId}"`)
        .build();

    beacon.on('newMessage', notification => console.log);
    beacon.start().catch(console.error);
  }
};
Run Code Online (Sandbox Code Playgroud)

在服务器端(用 JavaScript 编写的 Azure 函数),我有一条消息和一个 userId。我的问题是服务器如何知道哪个 SignalR 连接将连接到该特定用户?我能以某种方式告诉 SignalR 我是谁吗?

leo*_*ess 4

使用 Azure SignalR 服务和问题中的客户端代码我能够让它工作。我使用以下 Azure 函数来协商连接:

module.exports = async function (context, req, connectionInfo) {
  context.res.body = connectionInfo;
  context.done();
};
Run Code Online (Sandbox Code Playgroud)
{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "signalRConnectionInfo",
      "name": "connectionInfo",
      "userId": "{userId}",             // <----- IMPORTANT PART!
      "hubName": "chat",
      "direction": "in"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

以及另一个向特定用户发送消息的函数:

module.exports = async function (context, req) {
  const messageObject = req.body;
  return {
    "target": "newMessage",
    "userId": messageObject.userId,
    "arguments": [ messageObject.message]
  };
};
Run Code Online (Sandbox Code Playgroud)
{
  "disabled": false,
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "signalR",
      "name": "$return",
      "hubName": "chat",
      "direction": "out"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)