从.net代码和JavaScript调用SignalR中心

时间:2012-12-19 10:20:21

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

我有一个SignalR中心,我成功地从JQuery调用。

public class UpdateNotification : Hub
{
    public void SendUpdate(DateTime timeStamp, string user, string entity, string message)
    {
        Clients.All.UpdateClients(timeStamp.ToString("yyyy-MM-dd HH:mm:ss"), user, entity, message);       
    }
}

从JS成功发送的更新消息

var updateNotification = $.connection.updateNotification;
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] }).done(function () { });
updateNotification.server.sendUpdate(timeStamp, user, entity, message);

并成功收到

updateNotification.client.UpdateClients = function (timeStamp, user, entity, message) {

我无法理解如何从我的控制器中调用sendUpdate。

2 个答案:

答案 0 :(得分:6)

从您的控制器,在与集线器相同的应用程序中(而不是从其他地方,作为.NET客户端),您可以像这样进行集线器调用:

var hubContext = GlobalHost.ConnectionManager.GetHubContext<UpdateNotification>();
hubContext.Clients.All.yourclientfunction(yourargs);

https://github.com/SignalR/SignalR/wiki/Hubs脚附近看从集线器外部通过集线器广播

调用自定义方法有点不同。可能最好创建一个静态方法,然后您可以使用它来调用hubContext,如OP所在:Server to client messages not going through with SignalR in ASP.NET MVC 4

答案 1 :(得分:3)

以下是来自SignalR quickstart的示例 您需要创建集线器代理

public class Program
{
    public static void Main(string[] args)
    {
        // Connect to the service
        var hubConnection = new HubConnection("http://localhost/mysite");

        // Create a proxy to the chat service
        var chat = hubConnection.CreateHubProxy("chat");

        // Print the message when it comes in
        chat.On("addMessage", message => Console.WriteLine(message));

        // Start the connection
        hubConnection.Start().Wait();

        string line = null;
        while((line = Console.ReadLine()) != null)
        {
            // Send a message to the server
            chat.Invoke("Send", line).Wait();
        }
    }
}