SlideShare uma empresa Scribd logo
1 de 41
The HTML5 WebSocket API
Stockholm Web Monkeys
$ whoami
 David Lindkvist
   kontain.com/david-lindkvist
   twitter.com/ffdead


 Application Developer @F_i
   Web development is my passion!


 Drummer
   myspace.com/vildhjarta
   myspace.com/terminalfunction



                                    2
Agenda
 Why do we need WebSockets?

 What is it?

 How does it work?

 When can we use it?




                              3
Why?
       4
Why?
 Today’s web apps demand reliable event-driven
 communications
   “Real-time” (minimal latency)
   Full duplex


 Examples:
   Social networking
   Online games
   Collaborative platforms
   Financial applications
   etc...


                                                 5
Why? Problems with HTTP...
 It’s hard to achieve real-time apps, primarily due to the
 limitations of HTTP

 HTTP is half-duplex (traffic flows in only one direction
 at a time)

 HTTP adds latency and message overhead




                                                        6
Why? Simulate real-time?
 Polling (AJAX)
    Poll server for updates, wait at client


 Long polling (Comet)
    Poll server for updates, wait at the server; uses two
    connections and requires unnecessary complexity


 Used in Ajax applications to simulate real-time
    Leads to poor resource utilization...




                                                            7
Why? Polling
                              #$%%&'()*+,-&./,.0+/




                                                       !""#$%&"'()'"'$*+&,!&')-

                                   (picture from Kaazing)
   !"#$"%$!$
   1)233")4 5667&'()8$+9$+6.&$'
   !"#$"%$!$                                   !"
                                                !"


                                                                                  8
Why? Long Polling
                    #$%&'($))*%&+,-./*01.02-1




                                  (picture from Kaazing)

   !"#$"%$!$
   3+!""4+5 6778*%&+9$-:$-70*$%
   !"#$"%$!$                                 !"
                                             !"

                                                           9
Why? HTTP req/res overhead
GET /PollingStock//PollingStock HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5)
Gecko/20091102 Firefox/3.5.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300	     691 chars
Connection: keep-alive
Referer: http://localhost:8080/PollingStock/
Cookie: showInheritedConstant=false;
    showInheritedProtectedConstant=false; showInheritedProperty=false;
    showInheritedProtectedProperty=false; showInheritedMethod=false;
    showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false;
    showInheritedEffect=false
HTTP/1.x 200 OK
X-Powered-By: Servlet/2.5 Server: Sun Java System Application Server 9.1_02
Content-Type: text/html;charset=UTF-8
Content-Length: 321
Date: Sat, 07 Nov 2009 00:32:46 GMT
                                                                       Total 871 chars
                                                                            (example from Kaazing)


                                                                                      10
Why? Header traffic analysis
 Example network throughput for Polling HTTP req/resp
 headers:
   Use case A: 10,000 clients polling every 60 seconds
      Network throughput is (871 x 10,000)/60 = 145,166 bytes =
      1,161,328 bits per second (1.1 Mbps)
   Use case B: 10,000 clients polling every second
      Network throughput is (871 x 10,000)/1 = 8,710,000 bytes =
      69,680,000 bits per second (66 Mbps)
   Use case C: 100,000 clients polling every 10 seconds
      Network throughput is (871 x 100,000)/10 = 8,710,000 bytes =
      69,680,000 bits per second (66 Mbps)


                                                 (example statistics from Kaazing)


                                                                     11
What?
        12
What is a WebSocket?
 W3C/IETF Standard

 Uses the WebSocket protocol instead of HTTP

 True full-duplex communication channel
   Both UTF-8 strings and binary frames can be sent in any
   direction at the same time


 It’s not a raw TCP socket



                                                             13
What is a WebSocket?
 Connection established by “upgrading” from HTTP to
 WebSocket protocol

 Runs via port 80/443 - Proxy/Firewall friendly
    HTTP-compatible handshake
    Integrates with Cookie based authentication


 WebSockets and Secure WebSockets
    ws://
    wss://



                                                  14
What? Upgrade handshake

// browser request to the server
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
WebSocket-Protocol: sample

// server response
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket-Origin: http://example.com
WebSocket-Location: ws://example.com/demo
WebSocket-Protocol: sample




                                             15
What? Reduces Network Traffic
 Each message (“frame”) has only 2 bytes of overhead

 No latency from establishing new TCP connections for
 each HTTP message

 No polling overhead - only sends messages when
 there is something to send




                                                  16
What? Header traffic analysis
 Example network throughput for WebSocket req/res
 headers:
   Use case A: 10,000 frames every 60 seconds
      Network throughput is (2 x 10,000)/60 = 333 bytes = 2,664 bits
      per second (2.6 Kbps) [was 1.1 Mbps]
   Use case B: 10,000 frames every second
      Network throughput is (2 x 100,000)/1 = 20,000 bytes = 160,000
      bits per second (156 Kbps) [was 66 Mbps]
   Use case C: 100,000 frames every 10 seconds:
      Network throughput is (2 x 100,000)/10 = 20,000 bytes = 160,000
      bits per second (156 Kbps) [was 66 Mbps]

                                                  (example statistics from Kaazing)



                                                                       17
What? Overheard
 "Reducing kilobytes of data to 2 bytes...and reducing
 latency from 150ms to 50ms is far more than marginal.

 In fact, these two factors alone are enough to make
 WebSocket seriously interesting to Google.“

   - Ian Hickson (Google, HTML5 spec lead)




                                                       18
How?
       19
How? The WebSocket interface
[Constructor(in DOMString url, in optional DOMString protocol)]
interface WebSocket {
  readonly attribute DOMString URL;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSING = 2;
  const unsigned short CLOSED = 3;
  readonly attribute unsigned short readyState;
  readonly attribute unsigned long bufferedAmount;

  // networking
  attribute Function onopen;
  attribute Function onmessage;
  attribute Function onerror;
  attribute Function onclose;
  boolean send(in DOMString data);
  void close();
};
WebSocket implements EventTarget;




                                                                  20
How? The Javascript client
connect: function () {
    try {
        this.ws = new WebSocket(’ws://www.example.com’);
        this.ws.onopen = function (event) {/*...*/};
        this.ws.onclose = function (event) {/*...*/};
        this.ws.onmessage = messageListener;
    }
    catch(exception) {}
},
	
messageListener: function (event) {
    alert(’New message: ’ + event.data)
},

send: function (message) {
    if (this.ws) {
        this.ws.send(message);
    }
},




                                                           21
How? The server
 Server implementations (mostly experimental):

   Kaazing WebSocket Gateway (production since april 2009)
   phpwebsockets
   web-socket-ruby
   mod_pywebsocket
   JWebSocket
   Jetty WebSocketServlet

   and many more...




                                                         22
How? Jetty server example

public class MyServlet extends HttpServlet implements Servlet
{

     // trigger on HTTP GET request
     public void doGet(HttpServletRequest req, HttpServletResponse res) {}

     // trigger on HTTP POST request
     public void doPost(HttpServletRequest req, HttpServletResponse res) {}



    // doWebSocket() ???

}




                                                                              23
How? Jetty server example
public class ChatServiceServlet extends WebSocketServlet implements Servlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse res) {}
    public void doPost(HttpServletRequest req, HttpServletResponse res) {}



    // trigger on request to upgrade to WebSocket connection
    protected WebSocket doWebSocketConnect(HttpServletRequest req, String arg) {
	     	    return new ChatWebSocket();
    }



    // shared resource - needs to be thread safe!
    Set<ChatWebSocket> clients = new CopyOnWriteArraySet<ChatWebSocket>();
    class ChatWebSocket implements WebSocket {
         /* impl on next slide... */
    }

}




                                                                                   24
How? Jetty server example
class ChatWebSocket implements WebSocket {

    Outbound outbound;

    public void onConnect(Outbound outbound) {
        this.outbound = outbound;
        clients.add(this);
    }

    public void onMessage(byte frame, String data) {
        for (ChatWebSocket socket : clients) {
            try {
                socket.outbound.sendMessage(frame, data);
            }
            catch(IOException e) {}
        }
    }

    public void onDisconnect() {
        clients.remove(this);
    }
}




                                                            25
How? It’s not a silver bullet
 How should we handle the “close” event?

 Application must be prepared to reopen connection if
 close event was triggered unexpectedly
   Idle timeout
   Network errors




                                                    26
How? It’s not a silver bullet
 Keep-alives

   Sending keep-alive messages to prevent closing due to an idle
   timeout

   No timeout discovery available on the WebSocket

   Keep-alives don’t avoid the need for handling “close” events
      WiFi connections and mobile devices




                                                             27
How? It’s not a silver bullet
 Queues

   Buffer messages that failed to send due to a transient network
   problem

   Resend queue when connection is restored

   Important for both server and client




                                                             28
How? It’s not a silver bullet
 Timeouts

   Not all network problems are transient

   Can’t allow queues to grow for ever

   Applications need a timeout when user is considered to be
   disconnected

   Need to implement an explicit close message for application to
   distinguish between network failures and an orderly close



                                                               29
How? It’s not a silver bullet
 Message Retries

   Even with queues we can’t know for sure messages are
   delivered due to race condition
      If close event is triggered soon after a message was sent?


   For quality of service to be guaranteed an acknowledge
   message would have to be sent for each message

   Ideally a future version of WebSockets would support an
   orderly close event



                                                                   30
How? It’s not a silver bullet
 onclose handing, keep-alives, message queues,
 timeouts and retries, introduce more problems:

   If server goes down client will loop trying to reconnect
      Needs a retry backoff algorithm to reduce retries over time


   Message size can cause connection to die if it exceeds some
   resource limit on client or server
      Looks like a transient network error...
      Connection is restored and retries to send same message from
      queue...
      Infinite loop!



                                                                    31
When?
        32
When?
 Current browser support:




                   CHROME

                            33
When? Browser support
 Status of native WebSocket support for other browsers
 (2010-04-11):

   Firefox - targeted for the v3.7 release but not yet in 3.7a4pre

   Safari - announced for 4.x but no target date yet

   Opera - 10.x already 95% HTML5 compatible but WebSockets
   missing

   IE 8.x - 9.x unknown
                                                   (reference: jWebSocket project)



                                                                    34
When?
 Graceful degradation for the next ~10 years....

    Realtime apps:
       Java Applet TCP Socket
       Flash XMLSockets over TCP
       Long polling over HTTP

    Not so realtime apps:
       Polling using periodical pulls over HTTP




                                                   35
When?
 Providing fallbacks mean more work.

 More works sucks..

 Solution: Look for a client library which implements the
 WebSocket interface!
    Kaazing
    jWebSocket

    Users will be able to take advantage of true WebSockets when
    their browser supports it


                                                            36
When?
 Or... roll your own!

 Introducing the Graceful WebSocket:

    A jQuery plugin implementing the WebSocket interface

       One interface = one implementation

    Uses the native WebSocket if available

    Automatic fallback on HTTP polling



                                                           37
Get involved?
 Visit the Graceful WebSocket project over at Google
 Code:
   http://code.google.com/p/jquery-graceful-websocket/




                                                         38
Summary
 Allows us to write real-time, event driven applications

 Better resource utilization, less latency, less network
 overhead

 Browser support so far is poor

 Specification is not finalized




                                                       39
References?
 W3C The WebSocket API
 HTML5 Communications - Frank Greco (Kaazing)
 jfokus 2010
 http://en.wikipedia.org/wiki/Web_Sockets
 Greg Wilkins Jetty WebSocket Server
 Greg Wilkins Websocket Chat
 http://jwebsocket.org/




                                                40
Thanks! oh... and we are hiring!
 http://www.f-i.com/careers




                                   41

Mais conteúdo relacionado

Mais procurados

Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Arun Gupta
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaJames Falkner
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossugclkao
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaArun 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 DevelopersViktor Gamov
 
HTML5 WebSocket for the Real-Time Web and the Internet of Things
HTML5 WebSocket for the Real-Time Weband the Internet of ThingsHTML5 WebSocket for the Real-Time Weband the Internet of Things
HTML5 WebSocket for the Real-Time Web and the Internet of ThingsPeter Moskovits
 
WEB SOCKET 應用
WEB SOCKET 應用WEB SOCKET 應用
WEB SOCKET 應用Jerromy Lee
 
Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableGareth Marland
 
Going Live! with Comet
Going Live! with CometGoing Live! with Comet
Going Live! with CometSimon Willison
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsArun Gupta
 

Mais procurados (20)

WebSocket protocol
WebSocket protocolWebSocket protocol
WebSocket protocol
 
Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014Nuts and Bolts of WebSocket Devoxx 2014
Nuts and Bolts of WebSocket Devoxx 2014
 
Php push notifications
Php push notificationsPhp push notifications
Php push notifications
 
Asynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and JavaAsynchronous Web Programming with HTML5 WebSockets and Java
Asynchronous Web Programming with HTML5 WebSockets and Java
 
WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
J web socket
J web socketJ web socket
J web socket
 
Websockets at tossug
Websockets at tossugWebsockets at tossug
Websockets at tossug
 
Web sockets in Java
Web sockets in JavaWeb sockets in Java
Web sockets in Java
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Getting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in JavaGetting Started with WebSocket and Server-Sent Events in Java
Getting Started with WebSocket and Server-Sent Events in Java
 
Ws
WsWs
Ws
 
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
 
HTML5 WebSocket for the Real-Time Web and the Internet of Things
HTML5 WebSocket for the Real-Time Weband the Internet of ThingsHTML5 WebSocket for the Real-Time Weband the Internet of Things
HTML5 WebSocket for the Real-Time Web and the Internet of Things
 
WEB SOCKET 應用
WEB SOCKET 應用WEB SOCKET 應用
WEB SOCKET 應用
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
Websockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalableWebsockets in Node.js - Making them reliable and scalable
Websockets in Node.js - Making them reliable and scalable
 
HTML5 WebSockets
HTML5 WebSocketsHTML5 WebSockets
HTML5 WebSockets
 
Going Live! with Comet
Going Live! with CometGoing Live! with Comet
Going Live! with Comet
 
Time for Comet?
Time for Comet?Time for Comet?
Time for Comet?
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 

Semelhante a The HTML5 WebSocket API

Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享Chia Wei Tsai
 
Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax Wrajivmordani
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Sameer Segal
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketbrent bucci
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)Ericom Software
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsNaresh Chintalcheru
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioRick Copeland
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkFabio Tiriticco
 
Analyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAnalyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAriya Hidayat
 
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01purans
 
WebSockets On Fire
WebSockets On FireWebSockets On Fire
WebSockets On FireJef Claes
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketMauricio "Maltron" Leal
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 

Semelhante a The HTML5 WebSocket API (20)

Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享
 
Web-Socket
Web-SocketWeb-Socket
Web-Socket
 
Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax W
 
Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012Websockets - DevFestX May 19, 2012
Websockets - DevFestX May 19, 2012
 
V2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocketV2 peter-lubbers-sf-jug-websocket
V2 peter-lubbers-sf-jug-websocket
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
 
Building Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using WebsocketsBuilding Next Generation Real-Time Web Applications using Websockets
Building Next Generation Real-Time Web Applications using Websockets
 
Real-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.ioReal-Time Python Web: Gevent and Socket.io
Real-Time Python Web: Gevent and Socket.io
 
WebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! FrameworkWebSockets wiith Scala and Play! Framework
WebSockets wiith Scala and Play! Framework
 
Analyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAnalyzing the Performance of Mobile Web
Analyzing the Performance of Mobile Web
 
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerryjWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
jWebSocket MobileTechCon 2010 - WebSockets on Android, Symbian and BlackBerry
 
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
Jwebsocketmobiletechcon2010en 100912071225 Phpapp01
 
WebSockets On Fire
WebSockets On FireWebSockets On Fire
WebSockets On Fire
 
Enhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocketEnhancing Mobile User Experience with WebSocket
Enhancing Mobile User Experience with WebSocket
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 

Último

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
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
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 

Último (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
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.
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
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
 
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
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 

The HTML5 WebSocket API

  • 1. The HTML5 WebSocket API Stockholm Web Monkeys
  • 2. $ whoami David Lindkvist kontain.com/david-lindkvist twitter.com/ffdead Application Developer @F_i Web development is my passion! Drummer myspace.com/vildhjarta myspace.com/terminalfunction 2
  • 3. Agenda Why do we need WebSockets? What is it? How does it work? When can we use it? 3
  • 4. Why? 4
  • 5. Why? Today’s web apps demand reliable event-driven communications “Real-time” (minimal latency) Full duplex Examples: Social networking Online games Collaborative platforms Financial applications etc... 5
  • 6. Why? Problems with HTTP... It’s hard to achieve real-time apps, primarily due to the limitations of HTTP HTTP is half-duplex (traffic flows in only one direction at a time) HTTP adds latency and message overhead 6
  • 7. Why? Simulate real-time? Polling (AJAX) Poll server for updates, wait at client Long polling (Comet) Poll server for updates, wait at the server; uses two connections and requires unnecessary complexity Used in Ajax applications to simulate real-time Leads to poor resource utilization... 7
  • 8. Why? Polling #$%%&'()*+,-&./,.0+/ !""#$%&"'()'"'$*+&,!&')- (picture from Kaazing) !"#$"%$!$ 1)233")4 5667&'()8$+9$+6.&$' !"#$"%$!$ !" !" 8
  • 9. Why? Long Polling #$%&'($))*%&+,-./*01.02-1 (picture from Kaazing) !"#$"%$!$ 3+!""4+5 6778*%&+9$-:$-70*$% !"#$"%$!$ !" !" 9
  • 10. Why? HTTP req/res overhead GET /PollingStock//PollingStock HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 691 chars Connection: keep-alive Referer: http://localhost:8080/PollingStock/ Cookie: showInheritedConstant=false; showInheritedProtectedConstant=false; showInheritedProperty=false; showInheritedProtectedProperty=false; showInheritedMethod=false; showInheritedProtectedMethod=false; showInheritedEvent=false; showInheritedStyle=false; showInheritedEffect=false HTTP/1.x 200 OK X-Powered-By: Servlet/2.5 Server: Sun Java System Application Server 9.1_02 Content-Type: text/html;charset=UTF-8 Content-Length: 321 Date: Sat, 07 Nov 2009 00:32:46 GMT Total 871 chars (example from Kaazing) 10
  • 11. Why? Header traffic analysis Example network throughput for Polling HTTP req/resp headers: Use case A: 10,000 clients polling every 60 seconds Network throughput is (871 x 10,000)/60 = 145,166 bytes = 1,161,328 bits per second (1.1 Mbps) Use case B: 10,000 clients polling every second Network throughput is (871 x 10,000)/1 = 8,710,000 bytes = 69,680,000 bits per second (66 Mbps) Use case C: 100,000 clients polling every 10 seconds Network throughput is (871 x 100,000)/10 = 8,710,000 bytes = 69,680,000 bits per second (66 Mbps) (example statistics from Kaazing) 11
  • 12. What? 12
  • 13. What is a WebSocket? W3C/IETF Standard Uses the WebSocket protocol instead of HTTP True full-duplex communication channel Both UTF-8 strings and binary frames can be sent in any direction at the same time It’s not a raw TCP socket 13
  • 14. What is a WebSocket? Connection established by “upgrading” from HTTP to WebSocket protocol Runs via port 80/443 - Proxy/Firewall friendly HTTP-compatible handshake Integrates with Cookie based authentication WebSockets and Secure WebSockets ws:// wss:// 14
  • 15. What? Upgrade handshake // browser request to the server GET /demo HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: example.com Origin: http://example.com WebSocket-Protocol: sample // server response HTTP/1.1 101 Web Socket Protocol Handshake Upgrade: WebSocket Connection: Upgrade WebSocket-Origin: http://example.com WebSocket-Location: ws://example.com/demo WebSocket-Protocol: sample 15
  • 16. What? Reduces Network Traffic Each message (“frame”) has only 2 bytes of overhead No latency from establishing new TCP connections for each HTTP message No polling overhead - only sends messages when there is something to send 16
  • 17. What? Header traffic analysis Example network throughput for WebSocket req/res headers: Use case A: 10,000 frames every 60 seconds Network throughput is (2 x 10,000)/60 = 333 bytes = 2,664 bits per second (2.6 Kbps) [was 1.1 Mbps] Use case B: 10,000 frames every second Network throughput is (2 x 100,000)/1 = 20,000 bytes = 160,000 bits per second (156 Kbps) [was 66 Mbps] Use case C: 100,000 frames every 10 seconds: Network throughput is (2 x 100,000)/10 = 20,000 bytes = 160,000 bits per second (156 Kbps) [was 66 Mbps] (example statistics from Kaazing) 17
  • 18. What? Overheard "Reducing kilobytes of data to 2 bytes...and reducing latency from 150ms to 50ms is far more than marginal. In fact, these two factors alone are enough to make WebSocket seriously interesting to Google.“ - Ian Hickson (Google, HTML5 spec lead) 18
  • 19. How? 19
  • 20. How? The WebSocket interface [Constructor(in DOMString url, in optional DOMString protocol)] interface WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSING = 2; const unsigned short CLOSED = 3; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute Function onopen; attribute Function onmessage; attribute Function onerror; attribute Function onclose; boolean send(in DOMString data); void close(); }; WebSocket implements EventTarget; 20
  • 21. How? The Javascript client connect: function () { try { this.ws = new WebSocket(’ws://www.example.com’); this.ws.onopen = function (event) {/*...*/}; this.ws.onclose = function (event) {/*...*/}; this.ws.onmessage = messageListener; } catch(exception) {} }, messageListener: function (event) { alert(’New message: ’ + event.data) }, send: function (message) { if (this.ws) { this.ws.send(message); } }, 21
  • 22. How? The server Server implementations (mostly experimental): Kaazing WebSocket Gateway (production since april 2009) phpwebsockets web-socket-ruby mod_pywebsocket JWebSocket Jetty WebSocketServlet and many more... 22
  • 23. How? Jetty server example public class MyServlet extends HttpServlet implements Servlet { // trigger on HTTP GET request public void doGet(HttpServletRequest req, HttpServletResponse res) {} // trigger on HTTP POST request public void doPost(HttpServletRequest req, HttpServletResponse res) {} // doWebSocket() ??? } 23
  • 24. How? Jetty server example public class ChatServiceServlet extends WebSocketServlet implements Servlet { public void doGet(HttpServletRequest req, HttpServletResponse res) {} public void doPost(HttpServletRequest req, HttpServletResponse res) {} // trigger on request to upgrade to WebSocket connection protected WebSocket doWebSocketConnect(HttpServletRequest req, String arg) { return new ChatWebSocket(); } // shared resource - needs to be thread safe! Set<ChatWebSocket> clients = new CopyOnWriteArraySet<ChatWebSocket>(); class ChatWebSocket implements WebSocket { /* impl on next slide... */ } } 24
  • 25. How? Jetty server example class ChatWebSocket implements WebSocket { Outbound outbound; public void onConnect(Outbound outbound) { this.outbound = outbound; clients.add(this); } public void onMessage(byte frame, String data) { for (ChatWebSocket socket : clients) { try { socket.outbound.sendMessage(frame, data); } catch(IOException e) {} } } public void onDisconnect() { clients.remove(this); } } 25
  • 26. How? It’s not a silver bullet How should we handle the “close” event? Application must be prepared to reopen connection if close event was triggered unexpectedly Idle timeout Network errors 26
  • 27. How? It’s not a silver bullet Keep-alives Sending keep-alive messages to prevent closing due to an idle timeout No timeout discovery available on the WebSocket Keep-alives don’t avoid the need for handling “close” events WiFi connections and mobile devices 27
  • 28. How? It’s not a silver bullet Queues Buffer messages that failed to send due to a transient network problem Resend queue when connection is restored Important for both server and client 28
  • 29. How? It’s not a silver bullet Timeouts Not all network problems are transient Can’t allow queues to grow for ever Applications need a timeout when user is considered to be disconnected Need to implement an explicit close message for application to distinguish between network failures and an orderly close 29
  • 30. How? It’s not a silver bullet Message Retries Even with queues we can’t know for sure messages are delivered due to race condition If close event is triggered soon after a message was sent? For quality of service to be guaranteed an acknowledge message would have to be sent for each message Ideally a future version of WebSockets would support an orderly close event 30
  • 31. How? It’s not a silver bullet onclose handing, keep-alives, message queues, timeouts and retries, introduce more problems: If server goes down client will loop trying to reconnect Needs a retry backoff algorithm to reduce retries over time Message size can cause connection to die if it exceeds some resource limit on client or server Looks like a transient network error... Connection is restored and retries to send same message from queue... Infinite loop! 31
  • 32. When? 32
  • 33. When? Current browser support: CHROME 33
  • 34. When? Browser support Status of native WebSocket support for other browsers (2010-04-11): Firefox - targeted for the v3.7 release but not yet in 3.7a4pre Safari - announced for 4.x but no target date yet Opera - 10.x already 95% HTML5 compatible but WebSockets missing IE 8.x - 9.x unknown (reference: jWebSocket project) 34
  • 35. When? Graceful degradation for the next ~10 years.... Realtime apps: Java Applet TCP Socket Flash XMLSockets over TCP Long polling over HTTP Not so realtime apps: Polling using periodical pulls over HTTP 35
  • 36. When? Providing fallbacks mean more work. More works sucks.. Solution: Look for a client library which implements the WebSocket interface! Kaazing jWebSocket Users will be able to take advantage of true WebSockets when their browser supports it 36
  • 37. When? Or... roll your own! Introducing the Graceful WebSocket: A jQuery plugin implementing the WebSocket interface One interface = one implementation Uses the native WebSocket if available Automatic fallback on HTTP polling 37
  • 38. Get involved? Visit the Graceful WebSocket project over at Google Code: http://code.google.com/p/jquery-graceful-websocket/ 38
  • 39. Summary Allows us to write real-time, event driven applications Better resource utilization, less latency, less network overhead Browser support so far is poor Specification is not finalized 39
  • 40. References? W3C The WebSocket API HTML5 Communications - Frank Greco (Kaazing) jfokus 2010 http://en.wikipedia.org/wiki/Web_Sockets Greg Wilkins Jetty WebSocket Server Greg Wilkins Websocket Chat http://jwebsocket.org/ 40
  • 41. Thanks! oh... and we are hiring! http://www.f-i.com/careers 41

Notas do Editor