How SignalR broadcast the messages? - signalr

Have started using SignalR. Would like to clear few queries regarding how SignalR have implemented broadcasting basically how server is able to initiate the Communication ?
1> In normal scenario whenever we request for a let say .aspx page, the server renders the page and returns the reponse back to the client and the things is done
But How SignalR is able to continously able to execute in Background/Async in case of Ticker demo available on the ASP.net site.
I googled little bit and found IRegisteredObject is one of the way where the the object which need to be excuted continously need to register with HostingEnvironment but for that the class have to implement the IRegisteredObject interface but in case of ticker demo none of the class implements the IRegisteredObject interface.
Am I mssing something over here or SignalR uses totally different technique ?

SignalR utilizes 4 transports through which it handles data from the server. Only one transport is used at a time but SignalR has 4 to ensure server/client communication on a wide variety of devices/browsers. Here's the transports and a short technical description:
Long Polling, to receive data it uses an ajax request whose response is not released until there is data available on the server, once the server returns data on the held onto response the client then creates another request and waits for the next batch of data. To send data it creates a second ajax request.
Forever Frame, uses iframes through which the server pushes down javascript text which is then executed in the iframe, the iframe then propagates the execution up to the parent page which then handles the data. To send data SignalR uses ajax requests.
Server Sent Events, uses the EventSource object. Supported in nearly everything but IE. The EventSource object opens up a one way pipe through which the server can pump data through, allowing the client to receive data in real time. To send data SignalR uses ajax requests.
Web Sockets, uses the built-in browser WebSocket object which opens up a single, bi-directional channel through which data can be received and sent.
That's the essence of each of SignalR's transports, you can see an hour presentation in which David Fowler and Damian Edwards create a Lite version of SignalR here. It essentially highlights how SignalR works under the covers.

Related

Meteor - calling serverside methods from client

Are Meteor.methods they only way to call server-side functions from the client?
http://docs.meteor.com/#/full/meteor_methods
the docs don't make it clear that they are they only way, but the fact that they exist seems to imply they are the only way. What is their purpose?
There are several ways to communicate back and forth between the server and client in Meteor :
Using Meteor.methods to perform Remote Method Invokation on the server, these calls are initiated by the client, ask for a computation to be performed on the server and receive a result.
Using the Pub/Sub mechanism, the server publishes a set of data and the client is subscribing to a subset of this data, being notified in real-time of data-updates taking place in the server and thus receiving modifications.
Using plain old HTTP requests with the HTTP module.
So Meteor.methods are not the only way to execute some code on the server upon a client request.
Their purpose is usually to update the database by providing new values for server-side collections, as a matter of fact, client-side collection inserts and updates are implemented as Meteor.methods.
The Pub/Sub mechanism is used to propagate DB updates to every connected client and to make sure they receive only the minimal subset they need.
The HTTP communication is used by the server to send the initial source code (HTML/JS/CSS) of the app on load time as well as performing standard operations such as requesting and downloading a file.

Timeout for broadcasting message using SignalR

I am using SignalR for the 1st time in my asp.net c# web app.
I am using HTML 5 and JavaScript for my client web page.
In essence whenever my server has an image to 'push' to my clients it does so. Sometimes this can be quite frequent.
Now, I imagine during a 'busy' period' my client(s) could be 'over-whelmed' by the data being pushed by my server?
How does my server know that the message has been recieved by my client (or not) and then proceed to send the next one?
SignalR doesn't provide a built-in way to wait for a client to receive a message. This would be very difficult to do in the general case where someone might be using Clients.All, and clients might be connecting/reconnecting/disconnecting at the time the message is sent.
However, it is possible to manually acknowledge that you have received a message on the client (perhaps by calling some hub method on the server), and then continue to send the next message once the acknowledgement (ACK) for the previous one has been received.

How to Intercept ScaleoutMessage Broadcast: (Edited: How to send message directly to ServiceBus SignalR Backplane)

I have following scenario:
User request for certain resource on server, This request is long running task and very like 2~3 seconds to 10 seconds. We issue a JobTicket to user, As our user want to wait.
On receiving request we store that request in persistence storage and issue a token to user as JobTicket (GUID).
User make connection with Hub to get information about that GUID.
In Background:
We have WAS Hosted as well as Windows Service to perform some operation on that request.
On complete, WAS Hosted/Windows Service call our Web Application that job has been completed.
From there based on job Ticket we identify which user and on its connection we let user know its job has been completed.
Now we have farm of servers, we are using Windows Server On Prem ServiceBus 1.1 which is working fine, But challenge we have is that we are not able to intercept ServiceBus based backplane message broadcast and message is going to all the client. As we have farm, user intermediately may have drop connection and connected to other server based on load balancer so we need to have scale out using Service Bus as its kind of seamless to integrate and we are also using for our internal purpose in our application so we don't want to user any other mix in complex solution.
I have tried using IHubPipelineModule but still Scale out message broadcast not passing thru that, I tried to hookup SignalR code directly and debug thru it but its taking long. I don't want to mess-up something arbitrary in actual code. As I can see that in OnReceive I can see message are coming, but not able to follow further. I just need small mechanism that I can intercept broadcast message and make sure that it goes to client it intended and not all the client by wasting resources, and security concern as well.
Please help me on this issue, it's kind of stuck from last 4 days and not able to come to any solution and same time I want to go with establish pattern and don't want to fork any special build for this kind of small issues which I am sure one of you expert knows how I can do that seamlessly.
Thanks,
Shrenik
After lots of struggling and not finding straight forward way, I have found the way as below for someone else in future it might help.
Scenario:
1. Web Farm: Host External User facing Web Pages
2. Backend Process: Which is mix of WebApi, SharePoint, Windows Service etc.
User from Web Page submit some request and get a unique id as return back. Internally on receiving request, we queue that request to Service Bus using TopicClient for processing.
There are pool of Windows Service watching on Message on Service Bus using SubscriptionClient and process that message. On completion of process which can run from 5 seconds to 30 seconds and some cases even more. We need to inform client that its job done if its waiting on web page or waiting for completion notification.
In this story, We are using SignalR to push job completion notification to client.
Now my earlier problem is How I let know from windows service to web application that job is done so send notification to client who submitted request.
One way is we hosted another hub internally in web application, Windows service act as client and call web application hosted hub, and in that hub method it will call external facing hub method to propagate message to specific client who submitted request, for which we are using Single user Group.
And as we have register service bus as backplane it will propagate to other servers and then appropriate client will get notification. So this is ideal solution and should work in most cases.
In above approach we have one limitation that, how Windows Service connect to Web Client, as we donot have windows auth, but we have openid based auth with ADFS. Now in such case Web Application required special code in which provide separate userid or password for windows service to communicate or have windows authentication also allowed for that hub for service account of windows service.
I was trying and trying how to remove all this hopes between interserver communication and again management of extra security.
So I did below with simplicity, though it tooks me whole night to find our internal of SignalR. But it works:
Approach is to send message directly to ServiceBus Backplane, and as all Web Server already hooked-up with ServiceBus backplane then they will get message.
Unfortunately SignalR doesn't provide such mechanism to send message directly to Backplane. I think its on pub/sub model so they don't want somebody to hack in their system :). or its violation of their pattern, but its make sense, in my case because of different roles and security, I have simplify code as below:
Create a ServiceBusMessageBus instance in my code, Same way as Below: Though I have created separate instance and store till lifetime of Windows Service, so I don't create instance every time:
ServiceBusMessageBus serviceBusBackplane = new ServiceBusMessageBus(new DefaultDependencyResolver(), new ServiceBusScaleoutConfiguration(connectionString, appName));
Create a ClientHubInvocation Object: This is a message which actually get created in SignalR infrastructure when Backplane based message broadcast:
ClientHubInvocation hubData = new ClientHubInvocation
{
Args = new object[] { msg },
Hub = "JobStatusHub",
Method = "onJobStatus",
State = null,
};
Create a Message object which accept by ServiceBusMessageBus.Publish, Yes, so this is a method which actually get called on base class ScaleoutMessageBus.Publish. This class is actually responsible for sending message to topic and other subscribers on other server nodes. Why not use that directly. Now to create Message Object, You need following code:
Message backplaneMessage = new Message(
sourceId,
"hg-JobStatusHub." + name,
new ArraySegment(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(hubData))));
In above second parameter is something interesting,
In case if you want to publish to all the client then syntax is "h-", in my case specific group user, so syntax is "hg-.. You can check the code here: https://github.com/SignalR/SignalR/blob/bc9412bcab0f5ef097c7dc919e3ea1b37fc8718c/src/Microsoft.AspNet.SignalR.Core/Infrastructure/PrefixHelper.cs
Publish your message to backplane directly as below:
await serviceBusBackplane.Publish(backplaneMessage);
I wish this PrefixHelper class have been public.
Remember: This is not recommended way and doent insulate from future upgrade for SignalR, as its internal they may change so any upgrade might come with small hazale to change this code. But in summary this works. Hope SignalR Team provide some mechanisam out of box to send message directly to backplane instead.
Thanks

SignalR: Why choose Hub vs. Persistent Connection?

I've been searching and reading up on SignalR recently and, while I see a lot of explanation of what the difference is between Hubs and Persistent Connections I haven't been able to get my head around the next level, which is why would I choose one approach over the other?
From what I see in the Connection and Hubs section it seems that Hubs provide a topic system overlaying the lower-level persistent connections.
From the highly up-voted comment below:
Partially correct. You can get topics or groups in persistent connections as well. The big difference is dispatching different types of messages. For example you have different kinds of messages and you want to send different kinds of payloads. With persistent connections you have to embed the message type in the payload (see Raw sample) but hubs gives you the ability to do RPC over a connection (lets you call methods on on the client from the server and from the server to the client). Another big thing is model binding. Hubs allow you to pass strongly typed parameters to methods.
The example used in the documentation uses a chat room metaphor, where users can join a specific room and then only get messages from other users in the same room. More generically your code subscribes to a topic and then get just messages published to that topic. With the persistent connections you'd get all messages.
You could easily build your own topic system on top of the persistent connections, but in this case the SignalR team did the work for you already.
The main difference is that you can't do RPC with PersistentConnection, you can only send raw data. So instead of sending messages from the server like this
Clients.All.addNewMessageToPage(name, message);
you'd have to send an object with Connection.Broadcast() or Connection.Send() and then the client would have to decide what to do with that. You could, for example, send an object like this:
Connection.Broadcast(new {
method: "addNewMessageToPage",
name: "Albert",
message: "Hello"
});
And on the client, instead of simply defining
yourHub.client.addNewMessageToPage = function(name, message) {
// things and stuff
};
you'd have to add a callback to handle all incoming messages:
function addNewMessageToPage(name, message) {
// things and stuff
}
connection.received(function (data) {
var method = data.method;
window[method](data.name, data.message);
});
You'd have to do the same kind of dispatching on the server side in the OnReceived method. You'd also have to deserialize the data string there instead of receiving the strongly typed objects as you do with hub methods.
There aren't many reasons to choose PersistentConnection over Hubs. One reason I'm aware of is that it is possible to send preserialized JSON via PersistentConnection, which you can't do using hubs. In certain situations, this might be a relevant performance benefit.
Apart from that, see this quote from the documentation:
Choosing a communication model
Most applications should use the Hubs API. The Connections API could
be used in the following circumstances:
The format of the actual message sent needs to be specified.
The developer prefers to work with a messaging and dispatching model
rather than a remote invocation model.
An existing application that uses a messaging model is being ported to use SignalR.
Depending on your message structure, you might also get small perfomance benefits from using PersistentConnection.
You may want to take a look at the SignalR samples, specifically this here.
There are two ways to use SignalR: you can access it at a low level by overriding its PersistentConnection class, which gives you a lot of control over it; or you can let SignalR do all of the heavy lifting for you, by using the high level ‘Hubs’.
Persistent Connection is a lower level API, you can perform actions on more specific time when the connection is opened or closed, in most applications the Hub is the best choice
There are three major points to consider when comparing these two:
Message Format
Communication model
SignalR customization
With hubs message formatting is basically handled from you but with persistent connections the message is raw and has be tokenized and parsed back and forth. If the message size is important then also note that the payload of a persistent connection is much less that that of a hub.
When it comes to the communication model persistent connections basically have a function for sending and receiving messaging while hubs take a remote procedure call model with unique function per requirement.
When it comes to customization since persistent connections are more low level they may give you more control over customization.

Asynchronous web service call in ASP.NET/C#

We have an application that hits a web service successfully, and the data returned updates our DB. What I'm trying to do is allow the user to continue using other parts of our web app while the web service processes their request and returns the necessary data.
Is this asynchronous processing? I've seen some console app samples on the msdn site, but considering this is a web form using a browser I'm not sure those samples apply. What if the user closes the browser window mid request? Currently we're using the Message Queue which "waits" for the web service to respond then handles the DB update, but we'd really like to get rid of that.
I'm (obviously) new to async requests and could use some help figuring this out. Does anyone have some code samples or pertinent articles I could check out?
Yes, what you're describing is async processing.
The best solution depends to some degree on the nature of the web services call and how you want to handle the results. A few tips that might help:
One approach is to send a request from the initial web request to a background thread. This works best if your users don't need to see the results of the call as soon as it completes.
Another approach is to have your server-side code make an async web services call. This is the way to go if your users do need to see the results. The advantage of an async call on the server side is that it doesn't tie up an ASP.NET worker thread waiting for results (which can seriously impair scalability)
Your server-side code can be structured either as a web page (*.aspx) or a WCF service, depending on what you want to have it return. Both forms support async.
From the client, you can use an async XMLHTTP request (Ajax). That way, you will receive a notification event when the call completes.
Another approach for long-running tasks is to write them to a persistent queue using Service Broker. This works best for things that you'd like users to be able to start and then walk away from and see the results later, with an assurance that the task will be completed.
In case it helps, I cover each of these techniques in detail in my book, along with code examples: Ultra-Fast ASP.NET.
If you're not blocking for a method return you're doing asychronous processing. Have a look at Dino Esposito's article on using AJAX for server task checking.
You can perform asynchronous web service calls using both Web Service Enhancements (WSE) and Windows Communication Foundation (WCF) in your C# code. WSE is discontinued, so its use is not recommended. Generically speaking, if you were to terminate program execution in the middle of an asynchronous call before the response returned, nothing bad would happen; the client would simply not process the result, but the web service would still be able to perform its processing to completion.
If your client web application is responsible for updating the DB, then without anything else in your client code, quitting in the middle of an asynchronous operation would mean that the DB was not updated. However, you could add some code to your client application that prevented the browser from quitting entirely while it is waiting for an asynchronous response while preventing new web service calls from being run after Close is called (using Javascript).
You have 2 distinct communications here: (1) from web browser to web application and (2) from web application to web service.
diagram http://img697.imageshack.us/img697/6713/diagramo.png
There is no point of making (2) asynchronous: you still would have to wait for web service to finish processing request. If you end HTTP request from browser to web application the client would have no clue what the result of request was.
It is much better to make asynchronous request from web browser to your web application. Ajax is ideal for that. In fact, that's what it was created for. Here's couple of links to get you started:
jQuery Ajax
ASP.NET AJAX

Resources