SlideShare una empresa de Scribd logo
1 de 18
Introduction to SignalR
“Persistent connection” between clients and server in ASP.NET
Introduction to SignalR


     Why real-time & how ?



Users want the latest info, NOW !
Introduction to SignalR
Introduction to SignalR

        Where are we ? On the web !

       HTTP  request/response

   It is a unidirectional protocol stateless


Never designed for real-time communications
Introduction to SignalR
Introduction to SignalR
   HTML5 WebSockets

     Extension to HTTP
     Provide raw sockets over HTTP
     Full-duplex
     Traverses proxies


     Not every browser supports it
     Not every proxy server supports it
     Not every webserver supports it
     They are raw sockets !
Introduction to SignalR
                             SignalR
Create a “persistent connection” between client and
server allowing you to push data from server to client.
                 Abstracts away the transport
          Provides just one programming model

             Not an official Microsoft project yet




          For more details: https://github.com/SignalR/SignalR
Introduction to SignalR


The connection between clients & server is persisted
over best possible transport mechanism, which could
be a combination of long polling, periodic polling &
sockets. In this way transport layer is abstracted to
provide a seamless persistent connection
Introduction to SignalR
                 Two connection models
Hubs (high level)
Can communicate with 1..N clients
Abstraction over PersistentConnection
Route automatically mapped (/signalr/hubs)
Can send messages and call methods
SignalR defines the protocol


PersistentConnection (low level)
Can communicate with 1..N clients
Is an IHttpHandler
Requires a route to be defined
Limited to sending messages
You define the “protocol”
Introduction to SignalR

 <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script>
 <script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script>
 <script src="signalr/hubs" type="text/javascript"></script>



SignalR registers some code to run at application start time that finds all hubs in
your application. On the first request to signalr/hubs, the proxy is generated and
cached for the lifetime of the application.


If you navigate to signalr/hubs in your browser, you'll see a script that is
dynamically generated based on the hubs declared on the server. Each hub on the
server will become a property on the client side $.connection.myHub /
$.connection.
Introduction to SignalR
                                  Hubs (high level)
$(function () {
   // Proxy created on the fly
   var chat = $.connection.hubChat1;

      // Declare a function on hub so the server can invoke it
      chat.addMessage1 = function (message) {
         $('#messages').append('<li>' + message + '</li>');
      };

      // Call the chat method on the server
      $("#broadcast").click(function () {
          chat.send1($('#msg').val());
      });

      // Start the connection
      $.connection.hub.start();
});
Introduction to SignalR
                            Hubs (high level)
 public class HubChat1 : Hub
  {
    // Call the chat method on the server
    public void Send1(string message)
    {
       // Call the addMessage method on all clients
       Clients.addMessage1(message);
    }
  }

Invoking methods on the Clients property will broadcast that message to all
connected clients (see above). But there are some cases where we want to
send a message to specific clients. We can use the indexer on the Clients
object to specify a connection id.

 Clients[Context.ConnectionId].addMessage(data);
Introduction to SignalR
                                Hubs (high level)
    public class PaginaController : Controller
    {
      public ActionResult Index()
      {
         return View();
      }

        public ActionResult Command()
        {
          var context = GlobalHost.ConnectionManager.GetHubContext<HubChat1>();
          context.Clients.addMessage1(“Hello world”);
          return null;
        }
    }
If you call an action method into the controller, you can also call a javascript
callback. To get the context object for a hub, use this method.
    GlobalHost.ConnectionManager.GetHubContext<T>()
Introduction to SignalR



      DEMO
Introduction to SignalR
                     PersistentConnection (low level)

 $(function () {
    var connection = $.connection('/echo');

       connection.received(function (data) {
           $('#messages').append('<li>' + data + '</li>');
       });

       $("#broadcast").click(function () {
           connection.send($('#msg').val());
       });

       connection.start();
 });

The "PersistentConnection" requires a route to be defined, it is limited to sending
messages and you must define the protocol.
Introduction to SignalR
                PersistentConnection (low level)

public class MyEndPoint : PersistentConnection
{
  protected override Task OnConnectedAsync(IRequest request, string connId)
  {
     return Connection.Broadcast("Connection " + connectionId + " connected");
  }

    protected override Task OnReceivedAsync(IRequest request, string connId, string data)
    {
      return Connection.Broadcast("Connection " + connectionId+ " sent " + data);
    }

    protected override Task OnDisconnectAsync(string connId)
    {
      return Connection.Broadcast("Connection " + connectionId+ " disconncted");
    }
}
Introduction to SignalR



      DEMO
Introduction to SignalR



You can download the demo code at this link: http://sdrv.ms/RJgdUp

 There is also a video on YouTube: http://youtu.be/qUG0BQYfmLM

Más contenido relacionado

Último

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Último (20)

Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Destacado

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Destacado (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

Introduction to SignalR using mvc with ajax/javascript (async real-time web application)

  • 1. Introduction to SignalR “Persistent connection” between clients and server in ASP.NET
  • 2. Introduction to SignalR Why real-time & how ? Users want the latest info, NOW !
  • 4. Introduction to SignalR Where are we ? On the web ! HTTP  request/response It is a unidirectional protocol stateless Never designed for real-time communications
  • 6. Introduction to SignalR HTML5 WebSockets Extension to HTTP Provide raw sockets over HTTP Full-duplex Traverses proxies Not every browser supports it Not every proxy server supports it Not every webserver supports it They are raw sockets !
  • 7. Introduction to SignalR SignalR Create a “persistent connection” between client and server allowing you to push data from server to client. Abstracts away the transport Provides just one programming model Not an official Microsoft project yet For more details: https://github.com/SignalR/SignalR
  • 8. Introduction to SignalR The connection between clients & server is persisted over best possible transport mechanism, which could be a combination of long polling, periodic polling & sockets. In this way transport layer is abstracted to provide a seamless persistent connection
  • 9. Introduction to SignalR Two connection models Hubs (high level) Can communicate with 1..N clients Abstraction over PersistentConnection Route automatically mapped (/signalr/hubs) Can send messages and call methods SignalR defines the protocol PersistentConnection (low level) Can communicate with 1..N clients Is an IHttpHandler Requires a route to be defined Limited to sending messages You define the “protocol”
  • 10. Introduction to SignalR <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script> <script src="signalr/hubs" type="text/javascript"></script> SignalR registers some code to run at application start time that finds all hubs in your application. On the first request to signalr/hubs, the proxy is generated and cached for the lifetime of the application. If you navigate to signalr/hubs in your browser, you'll see a script that is dynamically generated based on the hubs declared on the server. Each hub on the server will become a property on the client side $.connection.myHub / $.connection.
  • 11. Introduction to SignalR Hubs (high level) $(function () { // Proxy created on the fly var chat = $.connection.hubChat1; // Declare a function on hub so the server can invoke it chat.addMessage1 = function (message) { $('#messages').append('<li>' + message + '</li>'); }; // Call the chat method on the server $("#broadcast").click(function () { chat.send1($('#msg').val()); }); // Start the connection $.connection.hub.start(); });
  • 12. Introduction to SignalR Hubs (high level) public class HubChat1 : Hub { // Call the chat method on the server public void Send1(string message) { // Call the addMessage method on all clients Clients.addMessage1(message); } } Invoking methods on the Clients property will broadcast that message to all connected clients (see above). But there are some cases where we want to send a message to specific clients. We can use the indexer on the Clients object to specify a connection id. Clients[Context.ConnectionId].addMessage(data);
  • 13. Introduction to SignalR Hubs (high level) public class PaginaController : Controller { public ActionResult Index() { return View(); } public ActionResult Command() { var context = GlobalHost.ConnectionManager.GetHubContext<HubChat1>(); context.Clients.addMessage1(“Hello world”); return null; } } If you call an action method into the controller, you can also call a javascript callback. To get the context object for a hub, use this method. GlobalHost.ConnectionManager.GetHubContext<T>()
  • 15. Introduction to SignalR PersistentConnection (low level) $(function () { var connection = $.connection('/echo'); connection.received(function (data) { $('#messages').append('<li>' + data + '</li>'); }); $("#broadcast").click(function () { connection.send($('#msg').val()); }); connection.start(); }); The "PersistentConnection" requires a route to be defined, it is limited to sending messages and you must define the protocol.
  • 16. Introduction to SignalR PersistentConnection (low level) public class MyEndPoint : PersistentConnection { protected override Task OnConnectedAsync(IRequest request, string connId) { return Connection.Broadcast("Connection " + connectionId + " connected"); } protected override Task OnReceivedAsync(IRequest request, string connId, string data) { return Connection.Broadcast("Connection " + connectionId+ " sent " + data); } protected override Task OnDisconnectAsync(string connId) { return Connection.Broadcast("Connection " + connectionId+ " disconncted"); } }
  • 18. Introduction to SignalR You can download the demo code at this link: http://sdrv.ms/RJgdUp There is also a video on YouTube: http://youtu.be/qUG0BQYfmLM