Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 248
JAG Avatar asked Jan 14 '23 17:01

JAG


2 Answers

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

like image 162
Jude Fisher Avatar answered Jan 31 '23 04:01

Jude Fisher


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();
        }
    }
}
like image 32
Jakub Konecki Avatar answered Jan 31 '23 06:01

Jakub Konecki