SignalR从Hub外广播不起作用。

7
根据这里的维基文章:https://github.com/SignalR/SignalR/wiki/Hubs 我可以通过这个方法让我的MVC应用程序使用Hub广播消息:
$(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的单独动态链接库中,它看起来像这样。
namespace ServerHub
{
    public class ChatterBox : Hub
    {

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

通过以上设置,我可以在不同的浏览器上浏览相同的URL,在一个浏览器上发送一条消息,所有其他浏览器都会反馈。

然而,现在我想从控制器中发送一条消息。

所以在我的MVC互联网应用程序(out-of-the-box),在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();
    }

但上述代码似乎没有起作用。没有出现错误信息或运行时错误。代码执行,只是我在其他浏览器上看不到消息。
我哪里做错了?
1个回答

11
您正在调用名为“say”的方法,但您的客户端上只定义了名为“addMessage”的方法。
更改为:
    context.Clients.All.say("HELLO FROM ABOUT");

收件人:

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

谢谢您指出那个错误,现在它可以工作了。但是当我在控制台应用程序中使用同样的代码时,它不起作用。我已经更新了我的主贴。 - Null Reference
1
开一个新的问题。在回答给出后,您无法更改它。 - davidfowl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接