What are the differences between On
and Subscribe
methods available in IHubProxy
interface. When should one use one over the other
What is a SignalR hub. The SignalR Hubs API enables you to call methods on connected clients from the server. In the server code, you define methods that are called by client. In the client code, you define methods that are called from the server.
SignalR is an abstraction over some of the transports that are required to do real-time work between client and server. SignalR first attempts to establish a WebSocket connection if possible. WebSocket is the optimal transport for SignalR because it has: The most efficient use of server memory.
Objective: Use SignalR for notification between Web API, and TypeScript/JavaScript based Web App, where Web API and the Web App is hosted in different domain. Enabling SignalR and CORS on Web API: Create a standard Web API project, and install the following NuGet packages: Microsoft.
Subscribe is lower level and you should really never have to use it. On provides friendlier overloads that allow for strong typing of arguments. Here's an example:
public class MyHub
{
public void Send(string message, int age)
{
Clients.All.send(message, age);
}
}
public void Main()
{
var connection = new HubConnection("http://myserver");
var proxy = connection.CreateHubProxy("MyHub");
var subscription = proxy.Subscribe("send");
subscription.Received += arguments =>
{
string name = null;
int age;
if (arguments.Count > 0)
{
name = arguments[0].ToObject<string>();
}
if (arguments.Count > 1)
{
age = arguments[1].ToObject<int>();
}
Console.WriteLine("Name {0} and age {1}", name, age);
};
}
public void Main()
{
var connection = new HubConnection("http://myserver");
var proxy = connection.CreateHubProxy("MyHub");
proxy.On<string, int>("send", (name, age) =>
{
Console.WriteLine("Name {0} and age {1}", name, age);
});
}
I hate to necro, but this thread lead me down a bit of a dark alleyway. It is in fact possible to use Reactive Extensions (Rx) to handle the subscriptions and in many cases this is preferable as it allows composition.
A decent enough article explaining the basics. The formatting is sadly a bit botched in the code examples but you can get there. https://www.safaribooksonline.com/blog/2014/02/10/signalr-rx-framework/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With