7

基于此处的 wiki 文章: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());
        });
    });
});

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

namespace ServerHub
{
    public class ChatterBox : Hub
    {

        public void Send(string message)
        {
            Clients.All.addMessage(message);
        }
    }
}

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

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

因此,在我开箱即用的 MVC Internet 应用程序中,在 HomeController 的 About 操作中,我添加了以下内容:

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();
    }

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

我哪里做错了?

4

1 回答 1

11

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

改变:

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

至:

    context.Clients.All.addMessage("HELLO FROM ABOUT");
于 2012-11-30T06:47:35.137 回答