首页 > 解决方案 > 客户端的回调不会从 signalR 后端触发

问题描述

我在服务器端无法与客户端通信时遇到问题。一旦从客户端发送数据,我就会在后端接收数据,但是,反之亦然(当数据被发送回客户端时)。

我的项目设置:

我尝试了以下但没有成功:

索引.aspx:

<script src="/js/third_party/jquery-3.3.1.min.js"></script>
<script src="/js/third_party/jquery-ui.min.js"></script>

<script src="/js/third_party/jquery.signalR-2.4.0.min.js"></script>
<script src='/signalr/js'></script>
<script src="/js/client.js"></script>

客户端.js:

var conn = null;

$(function () {

    $.connection.hub.stateChanged(connectionStateChanged);
    $.connection.hub.start({ waitForPageLoad: false });
    conn = $.connection.login;

    function connectionStateChanged(state) {

        switch (state.newState) {
            case 1: // Connected
                conn.server.announce('This is an announcement.'); // Works fine and sends the message
                break;
        }

    }

    // I'm using '.client', so there is no reason why this should not be triggered
    conn.client.onAnnounce = function (message) {
        alert(message); // Does NOT receive the message back
        debugger;
    }

登录.cs:

public class Login : Hub
{
    public void Announce(string message)
    {
        // I receive the data here from the client... but it does not get sent back to the client
        Clients.Caller.onAnnounce(message);
    }
}

启动.cs:

[assembly: OwinStartup(typeof(AutoPlayer.Startup))]
namespace SignalRTest
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

我希望服务器接收一条消息,服务器将相同的消息发送回客户端,并让客户端提醒该消息。

标签: javascriptc#asp.netsignalrsignalr.client

解决方案


经过数小时尝试不同的事情,这是由于这行代码:

$.connection.hub.start({ **waitForPageLoad: false** });

删除 'waitForPageLoad' 设置,或将其设置为 true 来修复它。

" waitForPageLoad - 确定 SignalR 是否应该等到页面完全加载后才开始连接(默认为 true)。 "

我认为这是由于客户端 JS 文件没有完全加载,当服务器回调客户端时('conn.client.onAnnounce' 还不存在)。如果真的是这种情况,我想我会在控制台中看到一个 JS 错误......但我猜不是。


推荐阅读