【问题标题】:Callback on client side does not get get triggered from signalR back end客户端的回调不会从 signalR 后端触发
【发布时间】:2019-05-22 19:59:28
【问题描述】:

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

我的项目设置:

  • 使用框架 4.6.2 创建了一个空的 ASP.NET 应用程序

  • 已安装 nuget 包 'Microsoft.AspNet.SignalR' v2.4.0

  • 使用 jQuery 3.3.1

  • 添加了启动类并插入了“app.MapSignalR();”进入 配置方法

  • 添加了一个集线器,该集线器具有一种与 客户

  • 添加了一个 js 文件,用于启动集线器并与 服务器

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

  • 使用框架 4.5
  • 使用旧版本的 jQuery
  • 记录数据 后端(我确实从客户端接收数据
  • 尝试将消息发送回所有客户端 (Clients.All),而不仅仅是调用者
  • 重新创建一个新的 signalR 项目
  • 确保没有 JS 错误
  • 在多个浏览器(Chrome 和 Edge)中本地运行

index.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>

client.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;
    }

Login.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);
    }
}

Startup.cs:

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

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

【问题讨论】:

    标签: javascript c# asp.net signalr signalr.client


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-09
      • 2014-07-22
      • 1970-01-01
      • 2023-04-04
      相关资源
      最近更新 更多