JAG
JAG

Reputation: 685

Invoke a SignalR hub from .net code as well as JavaScript

I have a SignalR hub, which i successfully call from 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);       
    }
}

update message sent successfully from JS like so

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

and received successfully like so

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

I can't work out how to call sendUpdate from within my controller.

Upvotes: 4

Views: 11674

Answers (2)

Jude Fisher
Jude Fisher

Reputation: 11294

From your controller, in the same application as the hub (rather than from elsewhere, as a .NET client), you make hub calls like this:

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

See Broadcasting over a Hub from outside of a Hub near the foot of https://github.com/SignalR/SignalR/wiki/Hubs

To call your custom method is a little different. Probably best to create a static method, which you can then use to call the hubContext, as the OP has here: Server to client messages not going through with SignalR in ASP.NET MVC 4

Upvotes: 6

Jakub Konecki
Jakub Konecki

Reputation: 46008

Here's an example from SignalR quickstart You need to create a hub proxy.

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

Upvotes: 3

Related Questions