$.connection.myHub.server.announce on clients 视图不起作用

问题描述

我在我的 ASP.NET MVC 项目中使用 SignalR 包。我想在客户端视图上显示警报消息,但它从未出现过。

这是我的 MyHub.cs 文件,包含客户端的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace Klien //my namespace
{
    public class MyHub : Hub
    {
        public void Announce(string message)
        {
            Clients.All.Announce(message);
        }
    }
}

这是我在 SignalR.js 文件中的代码

setTimeout(function () {
    $.connection.hub.start().done(function () {
        console.log("It Worked!");
        $.connection.myHub.server.announce("Connected!");
    })
    .fail(function () {
        alert("Error!");
    });
    $.connection.myHub.client.announce = function (message) {
        alert(message);
    };
        
},5000);

$.connection.hub 通过显示“It Worked!”成功运行控制台上的消息。当我尝试在控制台 console.log($.connection.myHub) 上检查时,它说已与 /signalr 连接,但实际上我想宣布警报消息“已连接!”在客户端视图。我使用 setTimeout 是因为如果我不提及它,代码 $.connection.hub.start().done 永远不会运行 (SignalR not always ready after start().done()?)。

解决方法

您需要根据文档在开始之前定义一种方法。

我会删除该超时,因为您实际上是每 5 秒创建一个不需要的新连接。如果用户断开连接,您可以在下面看到我如何尝试重新连接。

//your method here
$.connection.myHub.client.announce = function (message) {
    alert(message);
};

//Start the connection only after at least one method has been declared.
$.connection.hub
    .start()
    .done(function () { 
       //your server call here
    })
    .fail(function (error) {
        console.log("An error occurred connecting to the server.");
    });
$.connection.hub.disconnected(function () {
    setTimeout(function () {
        $.connection.hub.start();
    },5000); // Restart connection after 5 seconds.
});