繁体   English   中英

通过signalR客户特定的消息

[英]client specific message by signalR

我正在尝试向SignalR客户端发送消息,但不应将其广播给所有人,我浏览了许多有关clientId和组的文章,但没有给出简单的示例或要点。 我的客户代码如下:

proxy: null,

//Getting the connection object
connection = .hubConnection('url')

//Creating proxy
this.proxy = connection.createHubProxy('SignalRServerHub');
this.proxy.on('displayStatus', function (a) {
   SignalRMessageTableService.getDataFromServer()
});

//Starting connection
connection.start()
//we are able to capture connection.id here
//under .done function but not sure how to use

请让我逐步了解解决方案或任何文章参考,以便我轻松理解。

要使用connectionId响应特定的客户端,您可以执行以下操作:

       var connectionId = Context.ConnectionId;
       Clients.Client(connectionId).someMethod(resultValue);

或仅回复来电者:

    Clients.Caller.someMethod(resultValue);

这些调用是从您的中心类的公共方法中进行的,并执行相同的操作。

编辑:

看起来connection.start()应该扩展一点。 如果服务器要在调用者处返回数据或回调事件,则不需要处理connectionId。 这将由服务器完成,并由上面发布的方法进行处理。

尝试将connection.start()行更改为如下所示:

connection.start().done(function() {
    $('#someButton').click(function () {
        var param1 = $('#someField').val();
        var param2 = $('#someField2').val();
        this.proxy.invoke('myHubMethod', param1, param2, paramN);
    });
});

进行必要的更改以将此应用于您的实现。 此代码基于您在文档中找到的代码。 由于看起来您没有使用生成的代理,因此我们在代理上使用invoke方法来告诉我们要发送的方法和参数。 这还会将事件连接到id=someButton的按钮,单击该按钮将在myHubMethod上触发myHubMethod

替代方案将类似于(使用生成的代理):

this.proxy.server.myHubMethod(param1, param2, paramN);

您应该看一下《 ASP.NET SignalR Hubs API指南-JavaScript客户端》

如果要将消息发送给特定用户,则可以使用2.0版中的新方法

Clients.User(userId).send(message);

默认情况下,使用的用户ID是IPrincipal.Identity.Name 如果要使用自己的映射覆盖用户标识机制,请参阅此回复-https: //stackoverflow.com/a/21355406/2489038

暂无
暂无

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

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