简体   繁体   English

使用SignalR从服务器向客户端发送消息

[英]Sending Messages from the Server to the Client with SignalR

I have been reading this article from the documentation: 我一直在阅读文档中的这篇文章:

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

It says, I can send a message from the client to the server like so: 它说,我可以像这样从客户端向服务器发送消息:

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

But, how can I send a message from my server to the client? 但是,如何从服务器向客户端发送消息?

I was first following this tutorial http://www.codemag.com/Article/1210071 which explained that I need simply to do this: 我首先遵循了本教程http://www.codemag.com/Article/1210071 ,该教程说明我只需要这样做:

SendMessage("Index action invoked.");

With SendMessage() defined as: 使用SendMessage()定义为:

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

But, this doesn't work. 但是,这不起作用。 On my client side, my error is: 在我的客户端上,我的错误是:

Object # has no method 'activate' 对象#没有方法“激活”

The client side code that I am using is: 我正在使用的客户端代码是:

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

So, the question is, how can I send a simple message from my server to the client? 因此,问题是,如何从服务器向客户端发送简单消息?

Can someone show me a complete example of how to do this? 有人可以向我展示如何执行此操作的完整示例吗? I have seen the stock ticker example from the documentation, but it is kind of hard to understand/ apply. 我已经从文档中看到了股票行情自动收录器示例,但很难理解/应用。

From what I understand you are calling a function on client called sendMessage here 据我了解,您正在此处调用名为sendMessage的客户端上的函数

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

However, I don't see a definition for this function on client side. 但是,我没有在客户端看到此功能的定义。 Instead you have defined a function called activate(). 相反,您定义了一个称为activate()的函数。 Additionally, from my working code, I have defined the client side functions like this. 另外,从我的工作代码中,我已经定义了这样的客户端功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM