SlideShare a Scribd company logo
1 of 9
SignalR
Real-time Messaging
MINH NGUYEN
@LINKNODE APRIL, 2015
Web Communication Evolution
1. Http Communication: Http Request / Http Response (Uni-directional communication)
2. Ajax Http Communication: (Uni-directional)
3. SignalR Communication (Bi-directional) to broadcast message
+ Server broadcast means that communications sent to clients are initiated by the server.
Client
Normal
Server
SignalR
Server
http
request http
response
signalr
request
ClientClient
client
request
Client
Normal
Server
ajax
request
To Solve Common Issues
1. How to get live status from browser in real-time?
2. To display:
+ Live results: stock, betting, football/sport matches results …
+ Live progress: long-running import, upload,…
 Current Temporary Approach:
+ Periodically refresh the page to update status
 Good enough??? (delay, waste bandwidth, server load...)
 New Approach: SignalR
SignalR – How it works?
+ SignalR will use WebSockets of HTML5 when it's available, and gracefully fallback to other
techniques when it isn't.
+ Bi-directional communication:
1. Client invokes server’s methods (Javascript call C# methods)
2. Server invokes client’s methods (C# call Javascript methods)
3. Client invokes client’s methods !!!
SignalR – How it works?
browser 1 browser 2 browser 3
browser 4
SignalR
Server
SignalR – How it works?
1. Demo Simple Applications (Chat app, Moving square app)
2. How to add SignalR to ASP.Net application?
• Nuget package Microsoft.AspNet.SignalR / jQuery framework for Visual Studio 2012/13
• Create Hub class
• Send and receive messages from Hub to client
<script src="~/Scripts/jquery.signalR-1.1.3.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
$(function () {
var chat = $.connection.chatHub;
chat.client.clientCodeMethod = function (message) {
// Add the message to the page.
$('#discussion').append('<br>' + message);
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call server method on the hub.
chat.server.serverCodeMethod($('#message').val());
});
});
});
</script>
public ActionResult Contact()
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.clientCodeMethod("Admin: stop the chat");
return View();
}
public class ChatHub : Hub
{
public void ServerCodeMethod(string message)
{
Clients.All.clientCodeMethod(message);
}
}
dynamic function
Apply for VentusAR
1. Worker role progress statuses
Apply for VentusAR
1. Detect changes from Azure table to notify browser the current import status
private static List<BusinessObjects.WorkerNotification> _oldWorkerStatuses = new List<BusinessObjects.WorkerNotification>();
public static void VentusARTimerJob(object sender, ElapsedEventArgs e)
{
//detect worker status changes here
var allWorkerStatuses = WorkerStatustManager.GetNotificationForAllUser();
var changedWorkerStatuses = allWorkerStatuses.Where(n => !_oldWorkerStatuses.Exists(m => m.Equals(n))).ToList();
//update to old worker statuses
_oldWorkerStatuses = allWorkerStatuses;
if (changedWorkerStatuses.Any())
{
//Broadcast message to all relevant client pages using SignalR
var context = GlobalHost.ConnectionManager.GetHubContext<VentusHub>();
foreach (var changedWorkerStatus in changedWorkerStatuses)
{
context.Clients.All.addNewMessageToPage(changedWorkerStatus.PartitionKey, changedWorkerStatus.RowKey,
changedWorkerStatus.ProjectUID.ToString(), changedWorkerStatus.NotifyCode);
}
}
}
SignalR with Azure Mobile Service
1. Azure mobile service makes use of SingalR to push notification from Mobile service to all
connected apps.

More Related Content

What's hot

Sample of APK Analysis 2 - Mixer Box
Sample of APK Analysis 2 - Mixer BoxSample of APK Analysis 2 - Mixer Box
Sample of APK Analysis 2 - Mixer Box
Lin BH
 

What's hot (12)

Playing with cxf interceptor in mule
Playing with cxf interceptor in mulePlaying with cxf interceptor in mule
Playing with cxf interceptor in mule
 
Using RESTFUL APIs in ANGULARJS
Using RESTFUL APIs in ANGULARJSUsing RESTFUL APIs in ANGULARJS
Using RESTFUL APIs in ANGULARJS
 
Consumer Driven Contracts - A Deep Dive
Consumer Driven Contracts - A Deep DiveConsumer Driven Contracts - A Deep Dive
Consumer Driven Contracts - A Deep Dive
 
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-appsJSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
 
Asp.net mvc 4
Asp.net mvc 4Asp.net mvc 4
Asp.net mvc 4
 
EWD 3 Training Course Part 10: QEWD Sessions and User Authentication
EWD 3 Training Course Part 10: QEWD Sessions and User AuthenticationEWD 3 Training Course Part 10: QEWD Sessions and User Authentication
EWD 3 Training Course Part 10: QEWD Sessions and User Authentication
 
Angularjs & REST
Angularjs & RESTAngularjs & REST
Angularjs & REST
 
Android & Monkey Web Services
Android & Monkey Web ServicesAndroid & Monkey Web Services
Android & Monkey Web Services
 
Sample of APK Analysis 2 - Mixer Box
Sample of APK Analysis 2 - Mixer BoxSample of APK Analysis 2 - Mixer Box
Sample of APK Analysis 2 - Mixer Box
 
Ws security with mule
Ws security with muleWs security with mule
Ws security with mule
 
Using a simple Ruby program to interface with quickly provisioned cloud appli...
Using a simple Ruby program to interface with quickly provisioned cloud appli...Using a simple Ruby program to interface with quickly provisioned cloud appli...
Using a simple Ruby program to interface with quickly provisioned cloud appli...
 
Android HTTP Service
Android HTTP ServiceAndroid HTTP Service
Android HTTP Service
 

Similar to SignalR tutorial & best practices

Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
Deepak Gupta
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Viktor Gamov
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
Flavius-Radu Demian
 

Similar to SignalR tutorial & best practices (20)

Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
 
Fancy Features in Asp.Net Core SignalR
Fancy Features in Asp.Net Core SignalRFancy Features in Asp.Net Core SignalR
Fancy Features in Asp.Net Core SignalR
 
SignalR
SignalRSignalR
SignalR
 
Modern Web Development in 2015
Modern Web Development in 2015Modern Web Development in 2015
Modern Web Development in 2015
 
SignalR with asp.net
SignalR with asp.netSignalR with asp.net
SignalR with asp.net
 
Comet from JavaOne 2008
Comet from JavaOne 2008Comet from JavaOne 2008
Comet from JavaOne 2008
 
Signal r
Signal rSignal r
Signal r
 
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
 
Google Web Toolkits
Google Web ToolkitsGoogle Web Toolkits
Google Web Toolkits
 
SignalR Overview
SignalR OverviewSignalR Overview
SignalR Overview
 
Introduction to SignalR
Introduction to SignalRIntroduction to SignalR
Introduction to SignalR
 
signalr
signalrsignalr
signalr
 
Real-time ASP.NET with SignalR
Real-time ASP.NET with SignalRReal-time ASP.NET with SignalR
Real-time ASP.NET with SignalR
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
 
Reactive Application Using METEOR
Reactive Application Using METEORReactive Application Using METEOR
Reactive Application Using METEOR
 
GWT training session 3
GWT training session 3GWT training session 3
GWT training session 3
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
 
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...
SenchaCon 2016: How to Give your Sencha App Real-time Web Performance - James...
 
Reactive application using meteor
Reactive application using meteorReactive application using meteor
Reactive application using meteor
 

More from Minh Ng (6)

3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with Kinect3D Scanning & Reconstruction with Kinect
3D Scanning & Reconstruction with Kinect
 
WebGL - 3D programming
WebGL - 3D programmingWebGL - 3D programming
WebGL - 3D programming
 
Provider pattern practices
Provider pattern practicesProvider pattern practices
Provider pattern practices
 
Open Data practices
Open Data practicesOpen Data practices
Open Data practices
 
Entity framework practices
Entity framework practicesEntity framework practices
Entity framework practices
 
Monogame Content Pipeline practices
Monogame Content Pipeline practicesMonogame Content Pipeline practices
Monogame Content Pipeline practices
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data PlatformLess Is More: Utilizing Ballerina to Architect a Cloud Data Platform
Less Is More: Utilizing Ballerina to Architect a Cloud Data Platform
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
API Governance and Monetization - The evolution of API governance
API Governance and Monetization -  The evolution of API governanceAPI Governance and Monetization -  The evolution of API governance
API Governance and Monetization - The evolution of API governance
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

SignalR tutorial & best practices

  • 2. Web Communication Evolution 1. Http Communication: Http Request / Http Response (Uni-directional communication) 2. Ajax Http Communication: (Uni-directional) 3. SignalR Communication (Bi-directional) to broadcast message + Server broadcast means that communications sent to clients are initiated by the server. Client Normal Server SignalR Server http request http response signalr request ClientClient client request Client Normal Server ajax request
  • 3. To Solve Common Issues 1. How to get live status from browser in real-time? 2. To display: + Live results: stock, betting, football/sport matches results … + Live progress: long-running import, upload,…  Current Temporary Approach: + Periodically refresh the page to update status  Good enough??? (delay, waste bandwidth, server load...)  New Approach: SignalR
  • 4. SignalR – How it works? + SignalR will use WebSockets of HTML5 when it's available, and gracefully fallback to other techniques when it isn't. + Bi-directional communication: 1. Client invokes server’s methods (Javascript call C# methods) 2. Server invokes client’s methods (C# call Javascript methods) 3. Client invokes client’s methods !!!
  • 5. SignalR – How it works? browser 1 browser 2 browser 3 browser 4 SignalR Server
  • 6. SignalR – How it works? 1. Demo Simple Applications (Chat app, Moving square app) 2. How to add SignalR to ASP.Net application? • Nuget package Microsoft.AspNet.SignalR / jQuery framework for Visual Studio 2012/13 • Create Hub class • Send and receive messages from Hub to client <script src="~/Scripts/jquery.signalR-1.1.3.min.js"></script> <script src="~/signalr/hubs"></script> <script> $(function () { var chat = $.connection.chatHub; chat.client.clientCodeMethod = function (message) { // Add the message to the page. $('#discussion').append('<br>' + message); }; // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call server method on the hub. chat.server.serverCodeMethod($('#message').val()); }); }); }); </script> public ActionResult Contact() { var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>(); context.Clients.All.clientCodeMethod("Admin: stop the chat"); return View(); } public class ChatHub : Hub { public void ServerCodeMethod(string message) { Clients.All.clientCodeMethod(message); } } dynamic function
  • 7. Apply for VentusAR 1. Worker role progress statuses
  • 8. Apply for VentusAR 1. Detect changes from Azure table to notify browser the current import status private static List<BusinessObjects.WorkerNotification> _oldWorkerStatuses = new List<BusinessObjects.WorkerNotification>(); public static void VentusARTimerJob(object sender, ElapsedEventArgs e) { //detect worker status changes here var allWorkerStatuses = WorkerStatustManager.GetNotificationForAllUser(); var changedWorkerStatuses = allWorkerStatuses.Where(n => !_oldWorkerStatuses.Exists(m => m.Equals(n))).ToList(); //update to old worker statuses _oldWorkerStatuses = allWorkerStatuses; if (changedWorkerStatuses.Any()) { //Broadcast message to all relevant client pages using SignalR var context = GlobalHost.ConnectionManager.GetHubContext<VentusHub>(); foreach (var changedWorkerStatus in changedWorkerStatuses) { context.Clients.All.addNewMessageToPage(changedWorkerStatus.PartitionKey, changedWorkerStatus.RowKey, changedWorkerStatus.ProjectUID.ToString(), changedWorkerStatus.NotifyCode); } } }
  • 9. SignalR with Azure Mobile Service 1. Azure mobile service makes use of SingalR to push notification from Mobile service to all connected apps.