从中心外部进行的 SignalR 广播不起作用



基于这里的维基文章:https://github.com/SignalR/SignalR/wiki/Hubs

我能够让我的 MVC 应用程序通过我的集线器广播消息:

$(function () {
    // Proxy created on the fly          
    var chat = $.connection.chatterBox;
    // Declare a function on the chat hub so the server can invoke it          
    chat.client.addMessage = function (message) {
        $('#messages').append('<li>' + message + '</li>');
    };
    // Start the connection
    $.connection.hub.start().done(function () {
        $("#broadcast").click(function () {
            // Call the chat method on the server
            chat.server.send($('#msg').val());
        });
    });
});

我的中心位于名为 ServerHub.dll 的单独 DLL 中,如下所示

namespace ServerHub
{
    public class ChatterBox : Hub
    {
        public void Send(string message)
        {
            Clients.All.addMessage(message);
        }
    }
}

因此,通过上述设置,我可以在几个不同的浏览器上浏览到相同的URL,并且从一个浏览器发送消息将反映在所有其他浏览器中。

但是,我现在要做的是从控制器内部发送消息。

因此,在我的开箱即用的MVC互联网应用程序中,在HomeController,关于操作中,我添加了以下内容:

using ServerHub;
    public ActionResult About()
    {
        ViewBag.Message = "Your app description page.";
        var context = GlobalHost.ConnectionManager.GetHubContext<ChatterBox>();
        context.Clients.All.say("HELLO FROM ABOUT");
        return View();
    }

但上述似乎不起作用。没有错误消息或运行时错误。代码执行,只是我在其他浏览器上看不到该消息。

我哪里做错了?

您正在调用一个名为"say"的方法,并且您的客户端上只定义了一个名为"addMessage"的方法。

改变:

    context.Clients.All.say("HELLO FROM ABOUT");

自:

    context.Clients.All.addMessage("HELLO FROM ABOUT");

最新更新