简体   繁体   English

如何在SignalR中使用connectionId将消息发送给特定用户

[英]How can I send message to specific user with connectionId in SignalR

I have an asp.net classic website. 我有一个asp.net经典网站。 ive got SignalR basic functionality to work (where one client send messages to rest of the clients). 我已经使用了SignalR基本功能(其中一个客户端向其余客户端发送消息)。 but now i want to send Messages only to specific connectionsIDs. 但是现在我只想发送消息到特定的connectionsID。 I've found some solution via stackoverflow but It didn't work on my codes. 我已经通过stackoverflow找到了一些解决方案,但是对我的代码不起作用。 I have shared my c# code at below can you guys take a look at it please. 我在下面分享了我的C#代码,你们能看看吗。 my PROBLEM iS that I am able to trigger the hub method "Static_Send" but no way to trigger to the js trigger no response ! 我的问题是我能够触发集线器方法“ Static_Send”,但无法触发js却无法响应! any solution please ... 任何解决方案请...

Here is my hub class below; 这是我下面的枢纽课程;

public class ChatHub : Hub
{
        private static IHubContext hubContext =       GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        public static string ConnectionID;

        public void Send( string message, string connectionid)
        {
            Clients.Client(connectionid).addNewMessageToPage(message, connectionid);
        }

        public void SendProxy(string name, string message, string connectionid, IHubContext hubContext)
        {

            hubContext.Clients.All.addNewMessageToPage(name, message, connectionid);
        }

        public override Task OnConnected()
        {
            ConnectionID = Context.ConnectionId.ToString();
            string username = Context.User.Identity.Name;
            return base.OnConnected();
        }
        public static void Static_Send(string message, string connectionid)
        {
            //hubContext.Clients.All.addNewMessageToPage(name, message, connectionid);
            hubContext.Clients.Client(connectionid).addNewMessageToPage(message, connectionid);
          //  hubContext.Clients.All.addNewMessageToPage(message, connectionid);
        }

    }

the below code is content my Mvc controller method 以下代码是我的Mvc控制器方法的内容

    public async System.Threading.Tasks.Task<ActionResult> Tetikle()
{    
var hubConnection = new HubConnection("http://localhost:57714");
                var hubProxy = hubConnection.CreateHubProxy("ChatHub");
                await hubConnection.Start();
                var connectionID = hubConnection.ConnectionId;
}

JS codes JS代码

    $(function () {
        var parent = window.parent.document.body;
        var chat = $.connection.chatHub;

       // $.connection.hub.start();

        chat.client.addNewMessageToPage = function (message, connectionid) {
            debugger;
            console.info("11"+connectionid);
            $('.dropdown-menu .listview .lv-body', parent).prepend('<a class="lv-item" href="#">' +
                                                             '<div class="media">' +
                                                             '<div class="pull-left">' +
                                                             '<img class="lv-img-sm" src="img/profile-pics/1.jpg" alt="">' +
                                                             '</div>' +
                                                             ' <div class="media-body">' +
                                                             '<div class="lv-title">E-imza</div>' +
                                                             '<small class="lv-small">' + message + '</small>' +
                                                             '</div>' +
                                                             '</div>' +
                                                             '</a>');


        };
        $.connection.hub.start().done(function () {
            debugger;
        });

    });
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }



    //});

Where static method has been called in another MVC controller 在另一个MVC控制器中调用了静态方法的地方

[HttpPost]
        public ActionResult BasvuruCreate(Ruhsat model)
        {
ChatHub.Static_Send("aa", item.identity);

}

You need following: 您需要遵循以下条件:

  1. A method on server to send a message to single client with client ID. 服务器上将消息发送到具有客户端ID的单个客户端的方法。 This would be similar to sendProxy but this time instead of ALL you need to select connectionID (or for signalR 2.0 you can use iUserIdProvider as stated here by example passed to it. 这将类似于sendProxy,但是这次您需要选择connectionID(而不是ALL)(或者对于signalR 2.0,您可以使用传递给它的示例中所述的iUserIdProvider)
  2. You can use AddMessagetoPage function on client to add message or you can use different method of adding a private user message as well. 您可以在客户端上使用AddMessagetoPage函数添加消息,也可以使用其他方法添加私人用户消息。

If you understand the cycle of Send and read through https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections you will find that connectionID may not be best to keep hold of and you have username or something that would then resolve into client ID and then you send a message to them. 如果您了解发送和阅读https://docs.microsoft.com/zh-cn/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections的周期,则将找到该connectionID可能不是最好的选择,您拥有用户名或一些可以解析为客户端ID的信息,然后向他们发送消息。 You can try this with connection ID to at least resolve the problem that code is working with known connection IDs. 您可以尝试使用连接ID来解决此问题,以至少解决代码使用已知连接ID的问题。

You have OnConnected method where you have obtained both connectionID and username but you are not storing it anywhere so if a user connects from mobile and desktop the username is same but connection IDs are different. 您具有OnConnected方法,在该方法中您获得了connectionID和用户名,但没有将其存储在任何地方,因此,如果用户从移动设备和台式机进行连接,则用户名相同,但连接ID不同。 Similarly if a user logs in from chrome and IE both then you will have two connection IDs and one username. 同样,如果用户同时从chrome和IE登录,则您将拥有两个连接ID和一个用户名。 You will need to resolve this so from username obtain an array of connection IDs then then call client side method to send whatever you want to that hub. 您将需要解决此问题,以便从用户名获取连接ID数组,然后调用客户端方法将所需的任何内容发送到该集线器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM