MVC CORE SignalR仅向特定用户发送消息

时间:2019-05-04 14:06:56

标签: asp.net-core-mvc signalr

我正在使用SignalR Core和ASPNET Core 2.2,并尝试向单个用户发送消息。对于所有用户来说,一切正常。 Csharp代码

[HubMethodName("SendMessageToUser")]
public Task DirectMessage(string user, string message)
{
  //eg.user = abcd@gmail.com
  return Clients.User(user).SendAsync("ReceiveMessage", message);
}

JS代码

connection.on("ReceiveMessage", 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);
});

1 个答案:

答案 0 :(得分:0)

您可以使用特定用户的连接ID向其发送消息,以便 我需要创建一个这样的中心。当用户连接到signalR集线器时,GetConnectionId将返回该用户的连接ID

   public class ConnectionHub : Hub
        {
            public async Task Send(string userId)
            {
                var message = $"Send message to you with user id {userId}";
                await Clients.Client(userId).SendAsync("ReceiveMessage", message);
            }

            public string GetConnectionId()
            {
                return Context.ConnectionId;
            }
        }

然后在startup.cs中

services.AddSignalR();
app.UseSignalR(routes =>
{
  routes.MapHub<ConnectionHub>("/connectionHub");
});

然后是客户端代码

(function () {
        var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();

        connection.start().then(function () {
            console.log("connected");

            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    sessionStorage.setItem('conectionId', connectionId);
                    // Send the connectionId to controller
                }).catch(err => console.error(err.toString()));;


        });

        $("#sendmessage").click(function () {
            var connectionId = sessionStorage.getItem('conectionId');
            connection.invoke("Send", connectionId);
        });

        connection.on("ReceiveMessage", function (message) {
            console.log(message);
        });

    })();

首先,我在集线器中调用getConnectionId以获取用户连接ID,然后可以使用其连接ID向特定用户发送消息。

希望有帮助