SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere Àhnliche Inhalte

KĂŒrzlich hochgeladen

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...gurkirankumar98700
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂșjo
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

KĂŒrzlich hochgeladen (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

Empfohlen

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
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data ScienceChristy Abraham Joy
 
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
 

Empfohlen (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