Call SignalR Hub from .net code as well as JavaScript

I have a SignalR hub that 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 so that

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

and successfully got it

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

I cannot decide how to call sendUpdate from my controller.

+4
source share
2 answers

From your controller in the same application as the hub (and not from another place like the .NET client), you make the following calls:

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

See Transfer through a hub from outside the hub next to the note https://github.com/SignalR/SignalR/wiki/Hubs

Calling your custom method is slightly different. It is probably best to create a static method that you can then use to call hubContext, as the OP has here: Server messages for the client not passing through SignalR in ASP.NET MVC 4

+5
source

Here is an example from SignalR quickstart You need to create a proxy server . .

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

All Articles