【问题标题】:SignalR doesn't use 'on' subscription after connection to server is startedSignalR 在连接到服务器后不使用“开启”订阅
【发布时间】:2015-10-07 02:06:06
【问题描述】:

我让 SignalR 与 Angular 客户端一起工作,但如果在我订阅事件之前建立了连接,我无法让 proxy.on() 工作。

我的服务器方法在两个集线器上调用客户端方法pushToClient

var connection1 = $.hubConnection(); //Works fine since I started connection AFTER subscribing
var proxy1 = connection1.createHubProxy('clientPushHub');
proxy1.on('sendToClient', function (message) {
    console.log('This will work: ' + message);
});
connection.start();

var connection2 = $.hubConnection(); // Doesn't work when I start the connection BEFORE subscribing
var proxy2 = connection2.createHubProxy('clientPushHub');
connection2.start();
proxy2.on('sendToClient', function (message) {
    console.log('This will not work: ' + message);
});

如果我在启动 connection2 之前更改了一些设置,以便 proxy2 订阅 pushToClient,它可以正常工作。还尝试在 start().done() 回调中进行“on”订阅,但没有成功。

我已经下载并验证了this example 在订阅 连接时按预期工作,this ASP.NET article/section 特别提到如果您不使用生成的代理,您可以按此顺序执行操作,我没有。

this SO question 中对提问者有效的方法对我无效。

有什么我可能出错的想法吗?

【问题讨论】:

    标签: signalr


    【解决方案1】:

    基于此post,听起来您必须在调用 start 之前至少有一个事件侦听器。从那里您可以使用“on”功能添加更多事件处理程序。

    编辑:

    试试这个。

    proxy2.on('foo',function(){});
    connection2.start();
    proxy2.on('sendToClient', function (message) {
        console.log('This will not work: ' + message);
    });
    

    这也是来自你linked你发帖的文章:

    注意:通常在调用 start 方法建立连接之前注册事件处理程序。如果您想在建立连接后注册一些事件处理程序,您可以这样做,但您必须在调用 startmethod 之前注册至少一个事件处理程序。原因之一是应用程序中可能有许多 Hub,但如果您只使用其中一个 Hub,您不希望在每个 Hub 上触发 OnConnected 事件。建立连接后,集线器代理上存在客户端方法就是告诉 SignalR 触发 OnConnected 事件的原因。如果您在调用 start 方法之前没有注册任何事件处理程序,您将能够调用 Hub 上的方法,但不会调用 Hub 的 OnConnected 方法,也不会从服务器调用任何客户端方法。 em>

    【讨论】:

    • 也适合我。另外,感谢您指出文章中的 sn-p。我错过它的原因是我正在查看有关注册侦听器的部分,它说您可以在开始后进行。我没有想过通过启动我不久前进行的连接来回顾笔记。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多