如何使用C#从SignalR客户端的Hub类接收广播消息?

时间:2017-05-25 10:31:21

标签: signalr signalr-hub signalr.client

我有一个场景,其中一个客户端正在向Hub Class方法AddMessage发送请求,而该方法又应该向所有客户端(包括启动它的人)广播该消息。

问题是我能够从客户端调用Hub方法AddMessage,如下面的代码所示,但我找不到一种方法来处理客户端上的广播消息在Hub类中使用以下行。

Clients.All.NotifyMessageToClients(name, message);

SignalR Hub Class

using System;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;

public class SignalRChatHub : Hub
{
    public void AddMessage(string name, string message)
    {
        // Following call is supposed to notify all clients with passed parameters. 
        // They could have a method called NotifyMessageToClients to fetch the broadcasted message

        Clients.All.NotifyMessageToClients(name, message); 
    }
}

SignalR Client

using System;
using Microsoft.AspNet.SignalR.Client;

public partial class Default : System.Web.UI.Page
{
    HubConnection hubConnection;
    IHubProxy stockTickerHubProxy;

    public Default()
    {
        hubConnection = new HubConnection("http://localhost:6898/");
        stockTickerHubProxy = hubConnection.CreateHubProxy("SignalRChatHub");
    }

    async public void SendAddNotification(string msgFrom, string msg)
    {
        // Following line calls Addmessage method in SignalRChatHub class
        await stockTickerHubProxy.Invoke("Addmessage", "Ajendra", "Hello StackOverflow");
    }

    // I might need the method NotifyMessageToClients here... to receive broadcasted message
}

我对如何在jQuery中实现相同而不是在C#中创建客户端有一些想法,就像我上面所做的那样。我怎么做到这一点?

如果上述方法没有任何意义,请建议我使用正确的方法。

1 个答案:

答案 0 :(得分:3)

您需要像这样从服务器监听事件:

df = df.shift(6)

...例如,如果你需要在WPF中更新UI,你应该像这样实现你的事件:

public partial class Default : System.Web.UI.Page
{
    HubConnection hubConnection;
    IHubProxy stockTickerHubProxy;

    public Default()
    {
        hubConnection = new HubConnection("http://localhost:6898/");
        stockTickerHubProxy = hubConnection.CreateHubProxy("SignalRChatHub");

        // listen to server events...
        // n is "name" and m is "message", but you can change to "a" and "b" or anything else...
        stockTickerHubProxy.On<string, string>("NotifyMessageToClients", (n, m) =>
        {
            Console.WriteLine("Message received from server. Name: {0} | Message: {1}", n, m);
        });

    }

    // "async" methods should return Task instead of void....
    // unless they are event handlers for UI applications...
    public async Task SendAddNotification(string msgFrom, string msg)
    {
        // first, start the connection...
        await stockTickerHubProxy.Start();
        // Following line calls Addmessage method in SignalRChatHub class
        await stockTickerHubProxy.Invoke("Addmessage", "Ajendra", "Hello StackOverflow");

        // you don't stop the connection, otherwise you won't be able to receive calls from the server
    }

}

我建议您阅读this guide以获取更深入的详细信息。