SlideShare a Scribd company logo
1 of 22
Download to read offline
WebSockets 101
dhaval.dalal@software-artisan.com

       @softwareartisan
A
Real-time
Webapp
Polling
• “Simulate” real-time by making series of XHRs
    at regular intervals.
• Pulls Data from the server.

            Process                      Process
                                                      Web Server      Process                      Process                      Process
                      Respo




                                                   Respo




                                                                                Respo




                                                                                                             Respo




                                                                                                                                          Respo
       st




                                    st




                                                                 st




                                                                                              st




                                                                                                                           st
 Reque




                              Reque




                                                           Reque




                                                                                        Reque




                                                                                                                     Reque
                       nse




                                                    nse




                                                                                 nse




                                                                                                              nse




                                                                                                                                           nse
                                                             Browser
Problems with Polling
• Its a wasted request if there are no updates.
• Vice-versa, users may be working on “stale”
  data since the last update
• Each request creates new connection to the
  server.
• Each request causes exchange of HTTP headers
  (request and response), they consume
  Bandwidth.
• Not scalable
Long-Polling
• Solves the problem of extremes (wasted request
  or stale data) by pushing updates to clients as they
  happen.


           Process            Process
                                        Web Server
                                        Respo
                                                    Process            Process               Process
                     Resp




                                                                                 Res




                                                                                                       Respon
                                                              Respon
     est




                       st




                                                               uest




                                                                                   Request
                                          Request
                      Reque
    Requ




                                                                                  pon
                      onse




                                                              Req
                                         nse




                                                                                                        se
                                                               se




                                                                                   se
                                                Browser
How Long-Polling works
• Browser makes request to the server.
• Connection is kept open between the server and
  the browser.
• When an update arrives the connection is closed
  (sent as complete response 200 OK).
• The browser then initiates a new long-polling
  request for subsequent updates.
• Techniques
  •   XHR Style LP    •   IFrame

  •   Script Tag LP
Long-Polling Pros & Cons
• Pros
 •   Reduces latency for data-delivery.

• Cons.
 •   Each request creates new connection and causes
     exchange of HTTP headers, they consume Bandwidth.

 •   Not Scalable
     •   Request hangs until a response is ready to be delivered.

     •   Old Server software won’t work with this approach as they hold the thread
         for each request.
Long-Polling Scalability
• It demands a server software that does not
  hold thread on server for each request.
• Instead move towards asynchronous event-
  driven server architecture
 •   For e.g Nginx, Netty, Node.js etc... Servers

 •   Addresses the C10K (Concurrent 10,000
     connections) problem
Separate Upstream &
Downstream connections
• Downstream Connection.
  •   Is kept open between the server and the browser.

  •   Regular updates pushed through this connection.

  •   Messages are continuously parsed by the client as
      they arrive.

 • Upstream Connection
  •   Browser makes Ajax requests to send commands (i.e
      events that trigger action) to server.
Separate Connections:
     Pros & Cons
• Pros
 •   Offers lowest latency.

 •   Best for streaming needs.

• Cons
 •   Uses 2 Half-Duplex connections to simulate Full-
     Duplex.
     •   HTTP is a request/response protocol (Half-Duplex), not bi-directional


 •   Co-ordination overheads between two connections.

 •   Some browsers may not support more than two
     simultaneous connections.
Enter WebSockets
• Full-Duplex
  •   Exchange HTTP headers initially when the connection is
      established, after that its all data exchange.

  •   Uses less bandwidth.

• Significant Scalability with reduction in network
  traffic
  •   100 clients.

  •   100 * 10 clients.

  •   100 * 10 * 10 clients.
Fun time!
   Lets create a
WebSocket connection
Check Browser Support
• Use window.WebSocket to find out
• What to do if the browser does not support it?
 • use polyfills      (github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills)


   •   SockJS

   •   Atmosphere jQuery Plugin (Fallback to LP)

   •   Socket.io

   •   web-socket-js (Flash based)

   •   Kaazing Websocket Gateway (Commercial)

   •   Graceful Websocket jQuery Plugin (Fallback to LP)

   •   jQuery Socket (Supports WebSocket, Server-Sent Events, Streaming and LP)
WebSocket Servers
     Java             .NET           Python        Ruby          PHP
                                                               Extendible
      Jetty        SuperWebSocket    websockify    Goliath     Web Socket
                                                                 Server
                                                 web-socket-
  jWebSocket           Nugget       pywebsockets
                                                    ruby

     Netty            XSockets

    GlassFish

Apache Active MQ

    Tomcat
Architecture
                     1
                         Request                        Web
                         2 Serve Static Resources
                                                       Server
                    3 Initiate WebSocket Connection

                             4 Upgrade Connection


                                    5 Send Data       WebSocket
                     6 Receive Data
                                                       Server



Event driven on both sides of the WebSocket connection.
Async API
• Server Callbacks
 •   onopen - when the connection is established

 •   onclose - when the connection is closed

 •   onerror - when an error occurs

 •   onmessage - when a message is received from the
     server

• Client Transmissions
 •   send
How WS protocol works
•    When making a WS
     connection, initiated by
     HTTP request, client sends a
     connection “upgrade”
     request.

•    Server responds by
     upgrading the connection
     and switching protocols
• Handshake is complete when both client & server switch
 protocols

• After this, client and server can begin sending messages until
 •    either of them closes the connection

 •    there is some network problem
More fun!
  Using Jetty’s
WebSocketServlet.
Same-Origin Policy
• Prevents client-Side Webapp running from one
  origin to obtain data retrieved from another
  origin.
• Limits unsafe HTTP requests launched
  towards destinations that differ from the
  running application’s origin
 •   <script> element can execute content retrieve
     from foreign origins.
     •   Requires you to trust the server


 •   Bypass using JSONP
     •   Server needs to implement some logic to allow you to do this.
Cross-Origin Resource
      Sharing (CORS)
• Extends Same-Origin Policy
• Its a way of restricting the domains that can access
  services. 
  •   White-list domains that are allowed to access services

• The browser and in-browser applications are
  supposed to respect that, and sometimes the
  Services (server-side) may protect themselves.
  •   Use a CORS Filter

  •   Flash uses crossdomain.xml
Thank-you!
References
•   blog.caplin.com/2009/04/20/what-is-the-real-time-web/

•   leggetter.co.uk/2012/04/22/websockets-realise-comet-theyre-not-an-alternative.html

•   infrequently.org/2006/03/comet-low-latency-data-for-the-browser

•   jstorimer.com/js/2009/01/12/what-the-heck-is-jsonp.html

•   carloscarrasco.com/blog/posts/read/implementing-script-tag-long-polling-for-comet-applications

•   en.wikipedia.org/wiki/Comet_(programming)

•   en.wikipedia.org/wiki/C10k_problem

•   tomcatexpert.com/blog/2012/04/24/websockets-tomcat-7

•   github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

•   Peter Lubbers, HTML5 WebSocket DZone Refcardz

More Related Content

More from Dhaval Dalal

Mars rover-extension
Mars rover-extensionMars rover-extension
Mars rover-extensionDhaval Dalal
 
How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?Dhaval Dalal
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDDDhaval Dalal
 
Paradigms Code jugalbandi
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandiDhaval Dalal
 
Data Reconciliation
Data ReconciliationData Reconciliation
Data ReconciliationDhaval Dalal
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr20154-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015Dhaval Dalal
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8Dhaval Dalal
 
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar20153-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015Dhaval Dalal
 
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015Dhaval Dalal
 
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueCodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueDhaval Dalal
 
The tao-of-transformation-workshop
The tao-of-transformation-workshopThe tao-of-transformation-workshop
The tao-of-transformation-workshopDhaval Dalal
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with GroovyDhaval Dalal
 
Language portfolio
Language portfolioLanguage portfolio
Language portfolioDhaval Dalal
 
A case-for-graph-db
A case-for-graph-dbA case-for-graph-db
A case-for-graph-dbDhaval Dalal
 
Transition contours
Transition contoursTransition contours
Transition contoursDhaval Dalal
 
Healthy Code Magazine June-2014 Issue Midas-Touch-Article
Healthy Code Magazine June-2014 Issue Midas-Touch-ArticleHealthy Code Magazine June-2014 Issue Midas-Touch-Article
Healthy Code Magazine June-2014 Issue Midas-Touch-ArticleDhaval Dalal
 
Neo4j MySql MS-SQL comparison
Neo4j MySql MS-SQL comparisonNeo4j MySql MS-SQL comparison
Neo4j MySql MS-SQL comparisonDhaval Dalal
 

More from Dhaval Dalal (20)

Mars rover-extension
Mars rover-extensionMars rover-extension
Mars rover-extension
 
How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?How Is Homeopathy Near To Yoga?
How Is Homeopathy Near To Yoga?
 
Approaching ATDD/BDD
Approaching ATDD/BDDApproaching ATDD/BDD
Approaching ATDD/BDD
 
Paradigms Code jugalbandi
Paradigms Code jugalbandiParadigms Code jugalbandi
Paradigms Code jugalbandi
 
Data Reconciliation
Data ReconciliationData Reconciliation
Data Reconciliation
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
CodeRetreat
CodeRetreatCodeRetreat
CodeRetreat
 
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr20154-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
4-Code-Jugalbandi-destructuring-patternmatching-healthycode#apr2015
 
Jumping-with-java8
Jumping-with-java8Jumping-with-java8
Jumping-with-java8
 
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar20153-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
3-CodeJugalbandi-currying-pfa-healthycodemagazine#mar2015
 
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
CodeJugalbandi-Sequencing-HealthyCode-Magazine-Feb-2015
 
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-IssueCodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
CodeJugalbandi-Expression-Problem-HealthyCode-Magazine#Jan-2015-Issue
 
The tao-of-transformation-workshop
The tao-of-transformation-workshopThe tao-of-transformation-workshop
The tao-of-transformation-workshop
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
 
Language portfolio
Language portfolioLanguage portfolio
Language portfolio
 
Code jugalbandi
Code jugalbandiCode jugalbandi
Code jugalbandi
 
A case-for-graph-db
A case-for-graph-dbA case-for-graph-db
A case-for-graph-db
 
Transition contours
Transition contoursTransition contours
Transition contours
 
Healthy Code Magazine June-2014 Issue Midas-Touch-Article
Healthy Code Magazine June-2014 Issue Midas-Touch-ArticleHealthy Code Magazine June-2014 Issue Midas-Touch-Article
Healthy Code Magazine June-2014 Issue Midas-Touch-Article
 
Neo4j MySql MS-SQL comparison
Neo4j MySql MS-SQL comparisonNeo4j MySql MS-SQL comparison
Neo4j MySql MS-SQL comparison
 

Recently uploaded

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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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 TerraformAndrey Devyatkin
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 

Recently uploaded (20)

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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Web sockets primer

  • 3. Polling • “Simulate” real-time by making series of XHRs at regular intervals. • Pulls Data from the server. Process Process Web Server Process Process Process Respo Respo Respo Respo Respo st st st st st Reque Reque Reque Reque Reque nse nse nse nse nse Browser
  • 4. Problems with Polling • Its a wasted request if there are no updates. • Vice-versa, users may be working on “stale” data since the last update • Each request creates new connection to the server. • Each request causes exchange of HTTP headers (request and response), they consume Bandwidth. • Not scalable
  • 5. Long-Polling • Solves the problem of extremes (wasted request or stale data) by pushing updates to clients as they happen. Process Process Web Server Respo Process Process Process Resp Res Respon Respon est st uest Request Request Reque Requ pon onse Req nse se se se Browser
  • 6. How Long-Polling works • Browser makes request to the server. • Connection is kept open between the server and the browser. • When an update arrives the connection is closed (sent as complete response 200 OK). • The browser then initiates a new long-polling request for subsequent updates. • Techniques • XHR Style LP • IFrame • Script Tag LP
  • 7. Long-Polling Pros & Cons • Pros • Reduces latency for data-delivery. • Cons. • Each request creates new connection and causes exchange of HTTP headers, they consume Bandwidth. • Not Scalable • Request hangs until a response is ready to be delivered. • Old Server software won’t work with this approach as they hold the thread for each request.
  • 8. Long-Polling Scalability • It demands a server software that does not hold thread on server for each request. • Instead move towards asynchronous event- driven server architecture • For e.g Nginx, Netty, Node.js etc... Servers • Addresses the C10K (Concurrent 10,000 connections) problem
  • 9. Separate Upstream & Downstream connections • Downstream Connection. • Is kept open between the server and the browser. • Regular updates pushed through this connection. • Messages are continuously parsed by the client as they arrive. • Upstream Connection • Browser makes Ajax requests to send commands (i.e events that trigger action) to server.
  • 10. Separate Connections: Pros & Cons • Pros • Offers lowest latency. • Best for streaming needs. • Cons • Uses 2 Half-Duplex connections to simulate Full- Duplex. • HTTP is a request/response protocol (Half-Duplex), not bi-directional • Co-ordination overheads between two connections. • Some browsers may not support more than two simultaneous connections.
  • 11. Enter WebSockets • Full-Duplex • Exchange HTTP headers initially when the connection is established, after that its all data exchange. • Uses less bandwidth. • Significant Scalability with reduction in network traffic • 100 clients. • 100 * 10 clients. • 100 * 10 * 10 clients.
  • 12. Fun time! Lets create a WebSocket connection
  • 13. Check Browser Support • Use window.WebSocket to find out • What to do if the browser does not support it? • use polyfills (github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills) • SockJS • Atmosphere jQuery Plugin (Fallback to LP) • Socket.io • web-socket-js (Flash based) • Kaazing Websocket Gateway (Commercial) • Graceful Websocket jQuery Plugin (Fallback to LP) • jQuery Socket (Supports WebSocket, Server-Sent Events, Streaming and LP)
  • 14. WebSocket Servers Java .NET Python Ruby PHP Extendible Jetty SuperWebSocket websockify Goliath Web Socket Server web-socket- jWebSocket Nugget pywebsockets ruby Netty XSockets GlassFish Apache Active MQ Tomcat
  • 15. Architecture 1 Request Web 2 Serve Static Resources Server 3 Initiate WebSocket Connection 4 Upgrade Connection 5 Send Data WebSocket 6 Receive Data Server Event driven on both sides of the WebSocket connection.
  • 16. Async API • Server Callbacks • onopen - when the connection is established • onclose - when the connection is closed • onerror - when an error occurs • onmessage - when a message is received from the server • Client Transmissions • send
  • 17. How WS protocol works • When making a WS connection, initiated by HTTP request, client sends a connection “upgrade” request. • Server responds by upgrading the connection and switching protocols • Handshake is complete when both client & server switch protocols • After this, client and server can begin sending messages until • either of them closes the connection • there is some network problem
  • 18. More fun! Using Jetty’s WebSocketServlet.
  • 19. Same-Origin Policy • Prevents client-Side Webapp running from one origin to obtain data retrieved from another origin. • Limits unsafe HTTP requests launched towards destinations that differ from the running application’s origin • <script> element can execute content retrieve from foreign origins. • Requires you to trust the server • Bypass using JSONP • Server needs to implement some logic to allow you to do this.
  • 20. Cross-Origin Resource Sharing (CORS) • Extends Same-Origin Policy • Its a way of restricting the domains that can access services.  • White-list domains that are allowed to access services • The browser and in-browser applications are supposed to respect that, and sometimes the Services (server-side) may protect themselves. • Use a CORS Filter • Flash uses crossdomain.xml
  • 22. References • blog.caplin.com/2009/04/20/what-is-the-real-time-web/ • leggetter.co.uk/2012/04/22/websockets-realise-comet-theyre-not-an-alternative.html • infrequently.org/2006/03/comet-low-latency-data-for-the-browser • jstorimer.com/js/2009/01/12/what-the-heck-is-jsonp.html • carloscarrasco.com/blog/posts/read/implementing-script-tag-long-polling-for-comet-applications • en.wikipedia.org/wiki/Comet_(programming) • en.wikipedia.org/wiki/C10k_problem • tomcatexpert.com/blog/2012/04/24/websockets-tomcat-7 • github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills • Peter Lubbers, HTML5 WebSocket DZone Refcardz