【问题标题】:Sending Messages from the Server to the Client with SignalR使用 SignalR 从服务器向客户端发送消息
【发布时间】:2014-04-06 13:38:26
【问题描述】:

我一直在从文档中阅读这篇文章:

http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20-and-mvc-5

它说,我可以像这样从客户端向服务器发送消息:

$.connection.hub.start().done(function () {
    $('#sendmessage').click(function () {
        // Call the Send method on the hub. 
        chat.server.send($('#displayname').val(), $('#message').val());
        // Clear text box and reset focus for next comment. 
        $('#message').val('').focus();
    });
});

但是,如何从服务器向客户端发送消息?

我首先关注的是本教程http://www.codemag.com/Article/1210071,它解释说我只需要这样做:

SendMessage("Index action invoked.");

SendMessage() 定义为:

private void SendMessage(string message)
{
    GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message);
}

但是,这不起作用。在我的客户端,我的错误是:

对象#没有方法'activate'

我使用的客户端代码是:

$.connection.hub.start(function () {
    notificationHub.activate(function (response) {
        /*
        $("#target")
         .find('ul')
         .append($("<li></li>").html(response));
         */
        console.log(response);
    });
});

那么,问题是,我怎样才能从我的服务器向客户端发送一条简单的消息?

谁能给我一个完整的例子来说明如何做到这一点?我从文档中看到了股票代码示例,但它有点难以理解/应用。

【问题讨论】:

    标签: c# signalr asp.net-mvc-5


    【解决方案1】:

    据我了解,您在这里调用了客户端上的一个名为 sendMessage 的函数

    private void SendMessage(string message)
    {
        GlobalHost.ConnectionManager.GetHubContext<NotificationHub>().Clients.All.sendMessage(message);
    }
    

    但是,我没有在客户端看到此功能的定义。相反,您定义了一个名为 activate() 的函数。此外,从我的工作代码中,我已经定义了这样的客户端函数。

        var hub = $.connection.notificationHub;
        hub.client.sendMessage= function (data) {
    //some logic here
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多