SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
Server
              Sent
              Events
By Kornel Lesiński (@pornelski) for London JS, July 2011, http://lanyrd.com/2011/ldnjs03/
XHR




Everyone uses XML HTTP Request. AJAX is in every developers’ toolbox. And recently, WHATWG has re-invented TCP/
IP with WebSockets.
Web-
                               XHR
                                              Sockets




And a question has arisen: is there a room…
XHR                                         ?                                    Web-
                                                                                              Sockets




…for a third category of API in the middle – something between XHR and WebSockets? And browser vendors
pondered this for years as well. The bar is really high. In order to create a new category of API, it has to be far better
at some key things: it has to be very easy to use. It has to have great security. It must be compatible with browsers,
servers and proxies.
XHR                                 SSE                                         Web-
                                                                                            Sockets




And I think I’ve got something that is. And I’d like to show it to you to day. It’s called the iPad^W^WServer Sent
Events. It enables you to do fantastic things
Real-time chat

                           POST                                             SSE




You can create real-time chat application. A posted message can be pushed to everyone in the chat, instantly.
You can use it to watch your server logs and performance indicators in real time. It’s perfect for this.
GOOG 68.68 (12.98%) ADBE Someone has tweeted! OPR.OL 0.70 (2
                         -0.06 (-0.20%)


                               Someone has tweeted!
                                                                                       Someone has tweeted!
                                                       Someone has tweeted!

                                                                        Someone has tweeted!

                 Someone has tweeted!



                                                                                   Someone has tweeted!

                                       Someone has tweeted!


You can do boring stuff, like up-to-date stock tickers. And you can do more interesting stuff, like instant
notifications on your pages whenever a message is posted (as soon as sender presses Send). API for all of this is very
easy:
Very simple API
           var  source  =  new  EventSource("url");

           source.onmessage  =  function(event)  {
              alert(event.data);
           }



You create new event source, attach your event handler and read the data. That’s it!
• Automatically
              reconnects/resumes

           • Reuses connections
              to the same URL

           • Avoids blocking
              other HTTP traffic


The important thing is all the things you DON’T have to do. You don’t have to handle errors! Browser will the keep
connection alive for you. You don’t have to manage resources. If you create lots of EventSource objects, browser is
allowed to open just one connection and distribute events to all objects.
Browser knows that these are special long-lived connections and will ensure they’re handled properly and don’t hit
limits or block queues for other resources.
text/event-stream

                                  data:  Hello  World!n
                                  n




How does the stream look like? Couldn’t be simpler. It’s a text file! Lines prefixed data: set text to send (no length
limit), and empty line fires the event.

The protocol can do a bit more, but you don’t need to read a 200-page RFC.
ms

                   data:  Hello                                         retry:  1000
                   data:  World!
                   id:  123                                             event:  bark
                                                                        data:  Woof!
             Last-­‐Event-­‐Id:  123                                    :  comment



The whole thing fits on one slide. You don’t have protocol switching, framing, packet fragmentation or masking. To
send multiline data, prefix each line with data:. If you set ID, browser will send it back to you when it reconnects. This
way you can avoid sending same data twice (e.g. send scrollback in a chat app to new users only). Retry lets you
control how long to wait before reconnect. You can name events and use addEventListener(‘name’) to avoid huge
onmessage handler. Comments are for debug and heartbeat.
• Works with regular
               web servers

           • Works with HTTP
               proxies

           • Supports long
               polling (Comet)


SSE is just a download of a text file. You can use any server that can slowly generate a text file. You don’t need
special servers and complicated libraries for it!
Since it’s regular HTTP, it works with all proxies just fine. Even connection drops are not a problem, because it can
gracefully reconnect.
res.writeHead(200,  {"Content-­‐Type":  
                                               "text/event-­‐stream"});

       res.write("data:  "  +
                           JSON.stringify(stuff)  +
                           "nn");
       res.flush();



On the server it is very simple as well. Set content type and print lines. Note that I’m not including any special library
and I’m not doing any handshake.
Bonus tip here is to use JSON.stringify and JSON.parse, so you can use JS end-to-end. Flush is needed to actually
send data, instead of it sitting somewhere in buffers.
header("Content-­‐Type:  text/event-­‐stream");

       do  {
         echo  "data  :".json_encode($stuff)."nn";
         flush();
         sleep(1);
       }  while(!connection_aborted());



If you don’t have node.js I’m not sure what you’re doing on londonjs meetup, but you can generate event stream
even with clunky old PHP. You might be thinking – if I unleash this on millions of visitors, is my server going to look
like…
• Admin interfaces
                                                                • Watch server logs/
                                                                    traffic in real-time

                                                                • Moderators’
                                                                    notifications



is my server going to look like this? Yes, yes it will! Two ways around it: limit number of users. Use it for yourself in
admin, give it to few special users. Or, if you’re brave, you can do it on larger scale:
• Use long polling
                                                                retry:1000
                                                                & close connection

                                                             • Check
                                                               sys_getloadavg()



Instead of keeping connections open all the time, just close them from time to time. Browser will reconnect without
fuss. You control length of connection and control delay between reconnection, so you can have full spectrum
between persistent connection and polling. You can even be smart about this and watch server load – if it’s low, then
use persistent, when it’s too high, switch to polling and increase back-off time.
So, SSE can work with most servers. What about browsers?
11                        6                       5                   4                   6
            (9)                                                                                   beta

Peachy! Firefox has been lagging behind, but finally SSE is almost there.

There is something missing here, isn’t it? A certain browser built-in into an outdated OS of an American
corporation…
×                                           ×

Android of course! The other one doesn’t work either. But fear not! Fallback is easy. Since SSE is just a text file,
syntax is trivial to parse and it can fall back to polling, you can read it with XHR. It’s easy to write yourself, you can
find polyfill for this too. I’m pretty sure that Pusher guys have infiltrated the room by now, and they have dealt with
some server and client problems. Speaking of problems, there are a couple:
• Same-origin limitation
              (even port has to be the same!)

          • CORS in the future
          • No binary data (UTF-8 only)

You must use host and port for serving the page itself and the event stream. It’s annoying if you want to use Node.js
for the stream and have something else for regular pages. You can work around it by rewriting+proxying just the
stream URL with nginx or Varnish (this is another place where proxy compatibility pays off!)
History



First version was on Hixie’s blog in 2004 in response to “wouldn’t it be cool if server could fire any event?” And it was
really any event—you could remotely control page by firing mouse clicks and keyboard events!
<event-­‐source>




You could just hook stream with <event-source> element and the server could play with the page. Unsurprisingly, it turned out
to be difficult implement. Opera released first implementation in 2006, but Firefox had a patch for it a bit earlier. However, it
took years for the patch to be reviewed, fixed, reviewed, updated, etc. In 2009 the spec has been simplified to only allow custom
events, having element for JS-only API felt stupid. This broke Firefox’s patch. Updated patch missed Fx4 deadline. Fx5 wasn’t
making big changes. Finally Fx6 has it. I’d go mad if my patch took so long to land, but Wellington Fernando de Macedo—who
wrote most of it—in the meantime wrote WebSockets patch too!
Future

                                           • SMS
                                           • Push notifications


Mozilla hesitated adding SSE, which is a bit redundant with XHR multipart/replace hack and WebSockets, but eventually decided
to do it, hoping for the future: SSE is protocol-agnostic. It doesn’t have to work over HTTP. It might work over SMS or Apple-style
push notifications. An incoming event could launch Firefox mobile, which would open appropriate tab and fire event there—a real
push! It’s still far off thought, there isn’t even spec for it yet.
In short term, EventSource is coming to SharedWorkers, so you’ll be able to e.g. fire notification only in one tab that user is
looking at.
http://pornel.net/sse

   CC-BY-SA


• http://www.flickr.com/photos/gauri_lama/2672901420/
• http://www.flickr.com/photos/wheatfields/116783486/
• http://arrioch.deviantart.com/

Más contenido relacionado

La actualidad más candente

Application latency and streaming API
Application latency and streaming APIApplication latency and streaming API
Application latency and streaming APIstreamdata.io
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRShravan Kumar Kasagoni
 
Realtime web experience with signal r
Realtime web experience with signal rRealtime web experience with signal r
Realtime web experience with signal rRan Wahle
 
Introduction to Windows Azure Service Bus Relay Service
Introduction to Windows Azure Service Bus Relay ServiceIntroduction to Windows Azure Service Bus Relay Service
Introduction to Windows Azure Service Bus Relay ServiceTamir Dresher
 
Android rest client applications-services approach @Droidcon Bucharest 2012
Android rest client applications-services approach @Droidcon Bucharest 2012Android rest client applications-services approach @Droidcon Bucharest 2012
Android rest client applications-services approach @Droidcon Bucharest 2012Droidcon Eastern Europe
 
Eclipse Kapua messaging refactoring proposal
Eclipse Kapua messaging refactoring proposalEclipse Kapua messaging refactoring proposal
Eclipse Kapua messaging refactoring proposalHenryk Konsek
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...Panagiotis Kanavos
 
How to push data to a browser
How to push data to a browserHow to push data to a browser
How to push data to a browseralpha86
 
Multi-Process JavaScript Architectures
Multi-Process JavaScript ArchitecturesMulti-Process JavaScript Architectures
Multi-Process JavaScript ArchitecturesMark Trostler
 
Developing Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDeveloping Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDoris Chen
 
Link Header-based Invalidation of Caches
Link Header-based Invalidation of CachesLink Header-based Invalidation of Caches
Link Header-based Invalidation of Cachesmikekelly
 
Soap vs. rest - which is right web service protocol for your need?
Soap vs. rest -  which is right web service protocol for your need?Soap vs. rest -  which is right web service protocol for your need?
Soap vs. rest - which is right web service protocol for your need?Vijay Prasad Gupta
 
Secrets in Kubernetes
Secrets in KubernetesSecrets in Kubernetes
Secrets in KubernetesJerry Jalava
 
Ajax Patterns : Periodic Refresh & Multi Stage Download
Ajax Patterns : Periodic Refresh & Multi Stage DownloadAjax Patterns : Periodic Refresh & Multi Stage Download
Ajax Patterns : Periodic Refresh & Multi Stage DownloadEshan Mudwel
 
PharoDAYS 2015: Web 2.0 by Esteban Lorenzano
PharoDAYS 2015: Web 2.0 by Esteban LorenzanoPharoDAYS 2015: Web 2.0 by Esteban Lorenzano
PharoDAYS 2015: Web 2.0 by Esteban LorenzanoPharo
 

La actualidad más candente (20)

Application latency and streaming API
Application latency and streaming APIApplication latency and streaming API
Application latency and streaming API
 
zigbee
zigbeezigbee
zigbee
 
SOAP vs REST
SOAP vs RESTSOAP vs REST
SOAP vs REST
 
Building Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalRBuilding Realtime Web Applications With ASP.NET SignalR
Building Realtime Web Applications With ASP.NET SignalR
 
Wcf remaining
Wcf remainingWcf remaining
Wcf remaining
 
Realtime web experience with signal r
Realtime web experience with signal rRealtime web experience with signal r
Realtime web experience with signal r
 
Introduction to Windows Azure Service Bus Relay Service
Introduction to Windows Azure Service Bus Relay ServiceIntroduction to Windows Azure Service Bus Relay Service
Introduction to Windows Azure Service Bus Relay Service
 
Android rest client applications-services approach @Droidcon Bucharest 2012
Android rest client applications-services approach @Droidcon Bucharest 2012Android rest client applications-services approach @Droidcon Bucharest 2012
Android rest client applications-services approach @Droidcon Bucharest 2012
 
Realtime web
Realtime webRealtime web
Realtime web
 
Eclipse Kapua messaging refactoring proposal
Eclipse Kapua messaging refactoring proposalEclipse Kapua messaging refactoring proposal
Eclipse Kapua messaging refactoring proposal
 
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
The server side story:  Parallel and Asynchronous programming in .NET - ITPro...The server side story:  Parallel and Asynchronous programming in .NET - ITPro...
The server side story: Parallel and Asynchronous programming in .NET - ITPro...
 
How to push data to a browser
How to push data to a browserHow to push data to a browser
How to push data to a browser
 
Multi-Process JavaScript Architectures
Multi-Process JavaScript ArchitecturesMulti-Process JavaScript Architectures
Multi-Process JavaScript Architectures
 
Soap Vs Rest
Soap Vs RestSoap Vs Rest
Soap Vs Rest
 
Developing Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax PushDeveloping Revolutionary Web Applications using Comet and Ajax Push
Developing Revolutionary Web Applications using Comet and Ajax Push
 
Link Header-based Invalidation of Caches
Link Header-based Invalidation of CachesLink Header-based Invalidation of Caches
Link Header-based Invalidation of Caches
 
Soap vs. rest - which is right web service protocol for your need?
Soap vs. rest -  which is right web service protocol for your need?Soap vs. rest -  which is right web service protocol for your need?
Soap vs. rest - which is right web service protocol for your need?
 
Secrets in Kubernetes
Secrets in KubernetesSecrets in Kubernetes
Secrets in Kubernetes
 
Ajax Patterns : Periodic Refresh & Multi Stage Download
Ajax Patterns : Periodic Refresh & Multi Stage DownloadAjax Patterns : Periodic Refresh & Multi Stage Download
Ajax Patterns : Periodic Refresh & Multi Stage Download
 
PharoDAYS 2015: Web 2.0 by Esteban Lorenzano
PharoDAYS 2015: Web 2.0 by Esteban LorenzanoPharoDAYS 2015: Web 2.0 by Esteban Lorenzano
PharoDAYS 2015: Web 2.0 by Esteban Lorenzano
 

Destacado (16)

Conventions
ConventionsConventions
Conventions
 
Animales
AnimalesAnimales
Animales
 
Teleki pál levele a kormányzóhoz
Teleki pál levele a kormányzóhozTeleki pál levele a kormányzóhoz
Teleki pál levele a kormányzóhoz
 
Imenco Offshore Helicopter refuelling system presentation
Imenco Offshore Helicopter refuelling system presentationImenco Offshore Helicopter refuelling system presentation
Imenco Offshore Helicopter refuelling system presentation
 
Intro 3
Intro 3Intro 3
Intro 3
 
Portugal Powerpoint
Portugal PowerpointPortugal Powerpoint
Portugal Powerpoint
 
Ud3
Ud3Ud3
Ud3
 
The United Kingdom
The United KingdomThe United Kingdom
The United Kingdom
 
Iann nick 911 vs. 119
Iann nick 911 vs. 119Iann nick 911 vs. 119
Iann nick 911 vs. 119
 
Evaluation ppt
Evaluation ppt Evaluation ppt
Evaluation ppt
 
Array
ArrayArray
Array
 
Soci zip
Soci zipSoci zip
Soci zip
 
Podcasting
PodcastingPodcasting
Podcasting
 
Onthith hdh
Onthith hdhOnthith hdh
Onthith hdh
 
Kids to College WSJ Article
Kids to College WSJ ArticleKids to College WSJ Article
Kids to College WSJ Article
 
Internation
InternationInternation
Internation
 

Similar a Server-Sent Events (real-time HTTP push for HTML5 browsers)

Real-Time with Flowdock
Real-Time with FlowdockReal-Time with Flowdock
Real-Time with FlowdockFlowdock
 
Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009pauldix
 
MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011Mike Willbanks
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tourcacois
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
Experiences using CouchDB inside Microsoft's Azure team
Experiences using CouchDB inside Microsoft's Azure teamExperiences using CouchDB inside Microsoft's Azure team
Experiences using CouchDB inside Microsoft's Azure teamBrian Benz
 
Introduction to REST and Jersey
Introduction to REST and JerseyIntroduction to REST and Jersey
Introduction to REST and JerseyChris Winters
 
HTTP Plugin for MySQL!
HTTP Plugin for MySQL!HTTP Plugin for MySQL!
HTTP Plugin for MySQL!Ulf Wendel
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101Mike Willbanks
 
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...Alessandro Nadalin
 

Similar a Server-Sent Events (real-time HTTP push for HTML5 browsers) (20)

Real-Time with Flowdock
Real-Time with FlowdockReal-Time with Flowdock
Real-Time with Flowdock
 
NodeJS
NodeJSNodeJS
NodeJS
 
Nodejs + Rails
Nodejs + RailsNodejs + Rails
Nodejs + Rails
 
Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009Synchronous Reads Asynchronous Writes RubyConf 2009
Synchronous Reads Asynchronous Writes RubyConf 2009
 
Proposal
ProposalProposal
Proposal
 
Signal R 2015
Signal R 2015Signal R 2015
Signal R 2015
 
MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011MNPHP Scalable Architecture 101 - Feb 3 2011
MNPHP Scalable Architecture 101 - Feb 3 2011
 
Node.js: A Guided Tour
Node.js: A Guided TourNode.js: A Guided Tour
Node.js: A Guided Tour
 
Real time web apps
Real time web appsReal time web apps
Real time web apps
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
Experiences using CouchDB inside Microsoft's Azure team
Experiences using CouchDB inside Microsoft's Azure teamExperiences using CouchDB inside Microsoft's Azure team
Experiences using CouchDB inside Microsoft's Azure team
 
Introduction to REST and Jersey
Introduction to REST and JerseyIntroduction to REST and Jersey
Introduction to REST and Jersey
 
HTTP Plugin for MySQL!
HTTP Plugin for MySQL!HTTP Plugin for MySQL!
HTTP Plugin for MySQL!
 
Scalable Architecture 101
Scalable Architecture 101Scalable Architecture 101
Scalable Architecture 101
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...
Tips and Tricks for your Service Oriented Architecture @ CakeFest 2013 in San...
 
Web server
Web serverWeb server
Web server
 
0130225347
01302253470130225347
0130225347
 
Node.js primer
Node.js primerNode.js primer
Node.js primer
 
Best node js course
Best node js courseBest node js course
Best node js course
 

Último

Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
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
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 

Último (20)

Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
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
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
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
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 

Server-Sent Events (real-time HTTP push for HTML5 browsers)

  • 1. Server Sent Events By Kornel Lesiński (@pornelski) for London JS, July 2011, http://lanyrd.com/2011/ldnjs03/
  • 2. XHR Everyone uses XML HTTP Request. AJAX is in every developers’ toolbox. And recently, WHATWG has re-invented TCP/ IP with WebSockets.
  • 3. Web- XHR Sockets And a question has arisen: is there a room…
  • 4. XHR ? Web- Sockets …for a third category of API in the middle – something between XHR and WebSockets? And browser vendors pondered this for years as well. The bar is really high. In order to create a new category of API, it has to be far better at some key things: it has to be very easy to use. It has to have great security. It must be compatible with browsers, servers and proxies.
  • 5. XHR SSE Web- Sockets And I think I’ve got something that is. And I’d like to show it to you to day. It’s called the iPad^W^WServer Sent Events. It enables you to do fantastic things
  • 6. Real-time chat POST SSE You can create real-time chat application. A posted message can be pushed to everyone in the chat, instantly.
  • 7. You can use it to watch your server logs and performance indicators in real time. It’s perfect for this.
  • 8. GOOG 68.68 (12.98%) ADBE Someone has tweeted! OPR.OL 0.70 (2 -0.06 (-0.20%) Someone has tweeted! Someone has tweeted! Someone has tweeted! Someone has tweeted! Someone has tweeted! Someone has tweeted! Someone has tweeted! You can do boring stuff, like up-to-date stock tickers. And you can do more interesting stuff, like instant notifications on your pages whenever a message is posted (as soon as sender presses Send). API for all of this is very easy:
  • 9. Very simple API var  source  =  new  EventSource("url"); source.onmessage  =  function(event)  {   alert(event.data); } You create new event source, attach your event handler and read the data. That’s it!
  • 10. • Automatically reconnects/resumes • Reuses connections to the same URL • Avoids blocking other HTTP traffic The important thing is all the things you DON’T have to do. You don’t have to handle errors! Browser will the keep connection alive for you. You don’t have to manage resources. If you create lots of EventSource objects, browser is allowed to open just one connection and distribute events to all objects. Browser knows that these are special long-lived connections and will ensure they’re handled properly and don’t hit limits or block queues for other resources.
  • 11. text/event-stream data:  Hello  World!n n How does the stream look like? Couldn’t be simpler. It’s a text file! Lines prefixed data: set text to send (no length limit), and empty line fires the event. The protocol can do a bit more, but you don’t need to read a 200-page RFC.
  • 12. ms data:  Hello retry:  1000 data:  World! id:  123 event:  bark data:  Woof! Last-­‐Event-­‐Id:  123 :  comment The whole thing fits on one slide. You don’t have protocol switching, framing, packet fragmentation or masking. To send multiline data, prefix each line with data:. If you set ID, browser will send it back to you when it reconnects. This way you can avoid sending same data twice (e.g. send scrollback in a chat app to new users only). Retry lets you control how long to wait before reconnect. You can name events and use addEventListener(‘name’) to avoid huge onmessage handler. Comments are for debug and heartbeat.
  • 13. • Works with regular web servers • Works with HTTP proxies • Supports long polling (Comet) SSE is just a download of a text file. You can use any server that can slowly generate a text file. You don’t need special servers and complicated libraries for it! Since it’s regular HTTP, it works with all proxies just fine. Even connection drops are not a problem, because it can gracefully reconnect.
  • 14. res.writeHead(200,  {"Content-­‐Type":                                          "text/event-­‐stream"}); res.write("data:  "  +                    JSON.stringify(stuff)  +                    "nn"); res.flush(); On the server it is very simple as well. Set content type and print lines. Note that I’m not including any special library and I’m not doing any handshake. Bonus tip here is to use JSON.stringify and JSON.parse, so you can use JS end-to-end. Flush is needed to actually send data, instead of it sitting somewhere in buffers.
  • 15. header("Content-­‐Type:  text/event-­‐stream"); do  {  echo  "data  :".json_encode($stuff)."nn";  flush();  sleep(1); }  while(!connection_aborted()); If you don’t have node.js I’m not sure what you’re doing on londonjs meetup, but you can generate event stream even with clunky old PHP. You might be thinking – if I unleash this on millions of visitors, is my server going to look like…
  • 16. • Admin interfaces • Watch server logs/ traffic in real-time • Moderators’ notifications is my server going to look like this? Yes, yes it will! Two ways around it: limit number of users. Use it for yourself in admin, give it to few special users. Or, if you’re brave, you can do it on larger scale:
  • 17. • Use long polling retry:1000 & close connection • Check sys_getloadavg() Instead of keeping connections open all the time, just close them from time to time. Browser will reconnect without fuss. You control length of connection and control delay between reconnection, so you can have full spectrum between persistent connection and polling. You can even be smart about this and watch server load – if it’s low, then use persistent, when it’s too high, switch to polling and increase back-off time. So, SSE can work with most servers. What about browsers?
  • 18. 11 6 5 4 6 (9) beta Peachy! Firefox has been lagging behind, but finally SSE is almost there. There is something missing here, isn’t it? A certain browser built-in into an outdated OS of an American corporation…
  • 19. × × Android of course! The other one doesn’t work either. But fear not! Fallback is easy. Since SSE is just a text file, syntax is trivial to parse and it can fall back to polling, you can read it with XHR. It’s easy to write yourself, you can find polyfill for this too. I’m pretty sure that Pusher guys have infiltrated the room by now, and they have dealt with some server and client problems. Speaking of problems, there are a couple:
  • 20. • Same-origin limitation (even port has to be the same!) • CORS in the future • No binary data (UTF-8 only) You must use host and port for serving the page itself and the event stream. It’s annoying if you want to use Node.js for the stream and have something else for regular pages. You can work around it by rewriting+proxying just the stream URL with nginx or Varnish (this is another place where proxy compatibility pays off!)
  • 21. History First version was on Hixie’s blog in 2004 in response to “wouldn’t it be cool if server could fire any event?” And it was really any event—you could remotely control page by firing mouse clicks and keyboard events!
  • 22. <event-­‐source> You could just hook stream with <event-source> element and the server could play with the page. Unsurprisingly, it turned out to be difficult implement. Opera released first implementation in 2006, but Firefox had a patch for it a bit earlier. However, it took years for the patch to be reviewed, fixed, reviewed, updated, etc. In 2009 the spec has been simplified to only allow custom events, having element for JS-only API felt stupid. This broke Firefox’s patch. Updated patch missed Fx4 deadline. Fx5 wasn’t making big changes. Finally Fx6 has it. I’d go mad if my patch took so long to land, but Wellington Fernando de Macedo—who wrote most of it—in the meantime wrote WebSockets patch too!
  • 23. Future • SMS • Push notifications Mozilla hesitated adding SSE, which is a bit redundant with XHR multipart/replace hack and WebSockets, but eventually decided to do it, hoping for the future: SSE is protocol-agnostic. It doesn’t have to work over HTTP. It might work over SMS or Apple-style push notifications. An incoming event could launch Firefox mobile, which would open appropriate tab and fire event there—a real push! It’s still far off thought, there isn’t even spec for it yet. In short term, EventSource is coming to SharedWorkers, so you’ll be able to e.g. fire notification only in one tab that user is looking at.
  • 24. http://pornel.net/sse CC-BY-SA • http://www.flickr.com/photos/gauri_lama/2672901420/ • http://www.flickr.com/photos/wheatfields/116783486/ • http://arrioch.deviantart.com/