javascript - 客户端的回调不会从 signalR 后端触发
问题描述
我在服务器端无法与客户端通信时遇到问题。一旦从客户端发送数据,我就会在后端接收数据,但是,反之亦然(当数据被发送回客户端时)。
我的项目设置:
使用框架 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)中本地运行
索引.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();
}
}
}
我希望服务器接收一条消息,服务器将相同的消息发送回客户端,并让客户端提醒该消息。
解决方案
经过数小时尝试不同的事情,这是由于这行代码:
$.connection.hub.start({ **waitForPageLoad: false** });
删除 'waitForPageLoad' 设置,或将其设置为 true 来修复它。
" waitForPageLoad - 确定 SignalR 是否应该等到页面完全加载后才开始连接(默认为 true)。 "
我认为这是由于客户端 JS 文件没有完全加载,当服务器回调客户端时('conn.client.onAnnounce' 还不存在)。如果真的是这种情况,我想我会在控制台中看到一个 JS 错误......但我猜不是。
推荐阅读
- anaconda - 从lvm安装anaconda引导
- javascript - 在 JavaScript 中,为什么两个相同的属性函数会出现不同的输出?
- react-native - 如何优化 React Native 应用程序和 FalstList 的速度
- c# - 轰炸机的爆炸有时无法正常工作
- javascript - 使用 Spring Security 时,有什么方法可以使用引导模板登录?
- asp.net-mvc - MVC.NET 如何在编辑后保护提交表单
- mysql - 比较两个数据库表中的两个值
- angular - TSLint:禁止导入延迟加载的库:降级组件、在 AppModule 和角度引导中导入的模块
- javascript - Vue.js 应用程序从新页面的下拉菜单中打开 url 链接
- python - 如何通过python将生成的文本文件转换为tsv数据形式?