SlideShare a Scribd company logo
Implement Comet using PHP Dutch PHP Conference 2011 Jonas Mariën – King Foo www.king-foo.be
Jonas Mariën, King Foo www.king-foo.be Author “Zend Framework Web Services” (php|architect) Online since 93 (yep). PHP for fun since 96, professional since 2001. Master in Biological and Genetic Engineering, University of Leuven.
Comet = data push from server to client
Comet aka Reverse Ajax HTTP server Push Ajax Push HTTP streaming ... abused/umbrella term
Use case Example updates being pushed: ticker info
news items
chat messages
status updates
e-mail notifications
in-app messaging
monitoring feedback
feedback on processes that take time to complete
...
Push? But, but ... a browser pulls and the server responds, no? Fake push using polling trickery
Connection is kept open as long as possible
A giant hack
Does the trick for now
The Basics
Short polling Client tries to get something new from the server and polls at regular and short intervals.
Responsiveness at the cost of performance (on the server side). Wasteful in terms of resources.
Easy, but not really what we are looking for.
Not considered 'comet'.
Short polling function  getUpdate()  { $.ajax({ type: "POST", url: "server.php", data: "type=news&category=PHP", success : function(msg){ $('#feed').append(msg);/** we do something **/ setTimeout("getUpdate()", 2000); } }); } $(document).ready(function() { getUpdate(); }
Short polling demo
The forever frame An iframe keeps loading, never stops (or reloads occasionally)
Also called “streaming”
Dirty, e.g IE doesn't like this
The forever frame In the page: <script type=&quot;text/javascript&quot;>function updateResult(/** do something **/)</script>) <iframe style='width: 0px; height: 0px' src='./serverside.php'></iframe> On the server: <?php set_time_limit(0); header(&quot;Cache-Control: no-cache, must-revalidate&quot;); header(&quot;Expires: Mon, 24 Jul 1974 05:00:00 GMT&quot;); flush(); ob_flush();//if ob_start (implicitly) called before while(true) { $result = date('Y-m-d H:i:s'); echo '<script type=&quot;text/javascript&quot;>parent.updateResult(\''.$result.'\');</script>'; flush(); ob_flush(); $sleeptimer = rand(1, 15);  sleep($sleeptimer); }
The forever frame demo
XHR “XHR streaming”
Output 'busy' && sleep() on the server side untill finishing
We need to get  the status before  oncomplete/onsuccess Note: there is also multipart/x-mixed-replace  as part of XHR
XHR “ The XMLHttpRequest object can be in several states.  The readyState attribute must return the current state, which must be one of the following values” * http://www.w3.org/TR/XMLHttpRequest/#states UNSENT (0) The object has been constructed.  OPENED (1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.  HEADERS_RECEIVED (2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.  LOADING (3) The response entity body is being received.  DONE (4) The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
XHR Sine jQuery 1.5, no direct access to the underlying XHR object
No access to loading state
Can use a filter: http://bugs.jquery.com/ticket/8327
http://jsfiddle.net/d8ckU/1/ Plugin: http://plugins.jquery.com/project/ajax-http-stream
Mixed results using different browsers for direct XHR manipulation
XHR xhr.onreadystatechange = function() { if(http.readyState == 3  && http.status == 200) { //do something   document.write(xhr.responseText); } }
Long polling Longer intervals
Each time something  is returned from the  server, a new request  is started
Using XHR
Server: checks for updates for a few cycles and keeps a counter. If counter limit reached, 'false' or 'error' message goes back. If an update is available before that, exit the loop and return an 'ok' message with payload.
Long Polling function getUpdate(){ $.ajax({ type: &quot;GET&quot;, url: &quot;server.php&quot;, async: true,  cache: false, timeout:50000, success: function(data) {  /** do something **/ setTimeout ( 'getUpdate()', 1000 ); }, error: function(XMLHttpRequest, textStatus, errorThrown){ /**show error notice**/ setTimeout ( 'getUpdate()', &quot;20000&quot;); }, }); }; $(document).ready(function(){ getUpdate();  });
Long Polling <?php ...  $twitterSearch  = new Zend_Service_Twitter_Search('json'); $hashtag = 'dpc11'; if (isset($_GET['hashtag'])) { $hashtag = $_GET['hashtag']; } $result = false; while($result === false) { if (isset($_GET['since_id']) && $_GET['since_id'] > 0) { $since_id = (int) $_GET['since_id'] + 1; $searchResults  = $twitterSearch->search($hashtag, array('lang' => 'en', 'rpp' => 30,'since_id' => $since_id)); } else { $searchResults  = $twitterSearch->search($hashtag, array('lang' => 'en','rpp' => 30)); } if (isset($searchResults['results']) && count($searchResults['results'])) { $result = json_encode($searchResults['results'][0]); } } echo $result;
Long Polling demo
Thoughts & notes Piggybacking
Long polling issues: Requests are kept open for a while
Objects (other then the ones being pulled/pushed) on server side can be changed, need to have these changes fed to the client. Piggybacking to the rescue again?
One or more long polling requests open and then an AJAX call: might give you browser problems with simultaneous requests
Server performance: we need event driven solutions (message queues and/or something like node.js) to fix this
Proxies (chunking stuff) and firewalls (dropping long connections). Some Comet libs (next slides) try to detect intermediate proxies Comet is not mature. Uses HTTP against most of the basic assumptions and no real standards available. Not a real standard.
Thoughts & Notes Performance is the biggest problem A Comet server should be able to handle as much connections as fast as possible, with a high troughput and low latency.  Long polling requests stay idle for a while, so claiming a thread is not ok.
Frameworks/Toolkits
DWR Direct Web Remoting  (http://directwebremoting.org)
Nice, but Java  only
Fallback different  polling mechanisms
Dynamic Javascript  generation
Attempts at PHP implementations, one could use something like json-rpc to mimic this Could use a Java bridge from PHP perhaps?
Cometd & Bayeux Dojo Foundation
Cometd: reference implementation (in Java, Perl and Python). Java implementation uses Jetty.
Bayeux: protocol, JSON for request/response
Handshake + Publish/Subscribe

More Related Content

PDF
Symfony2 Components - The Event Dispatcher
Sarah El-Atm
 
PPT
Real Time Event Dispatcher
Peter Dietrich
 
PDF
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
PPT
Assurer - a pluggable server testing/monitoring framework
Gosuke Miyashita
 
PDF
Comet with node.js and V8
amix3k
 
KEY
Plack - LPW 2009
Tatsuhiko Miyagawa
 
PPT
How Danga::Socket handles asynchronous processing and how to write asynchrono...
Gosuke Miyashita
 
PDF
AnyMQ, Hippie, and the real-time web
clkao
 
Symfony2 Components - The Event Dispatcher
Sarah El-Atm
 
Real Time Event Dispatcher
Peter Dietrich
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
Assurer - a pluggable server testing/monitoring framework
Gosuke Miyashita
 
Comet with node.js and V8
amix3k
 
Plack - LPW 2009
Tatsuhiko Miyagawa
 
How Danga::Socket handles asynchronous processing and how to write asynchrono...
Gosuke Miyashita
 
AnyMQ, Hippie, and the real-time web
clkao
 

What's hot (20)

PDF
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
PDF
Ruby HTTP clients comparison
Hiroshi Nakamura
 
ODP
An Introduction to Windows PowerShell
Dale Lane
 
KEY
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
PDF
Choosing a Javascript Framework
All Things Open
 
PPT
Writing Pluggable Software
Tatsuhiko Miyagawa
 
KEY
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
PDF
Using Websockets with Play!
Andrew Conner
 
PDF
Tornado Web Server Internals
Praveen Gollakota
 
PDF
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
Matthias Noback
 
PPTX
PowerShell: Automation for everyone
Gavin Barron
 
PPTX
Tornado web
kurtiss
 
PPTX
Python, async web frameworks, and MongoDB
emptysquare
 
PPTX
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Barel Barelon
 
PDF
Rack Middleware
LittleBIGRuby
 
PDF
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PPT
Perlbal Tutorial
Takatsugu Shigeta
 
PPT
Servlets
Manav Prasad
 
PDF
Microservice Teststrategie mit Symfony2
Per Bernhardt
 
Selenium sandwich-3: Being where you aren't.
Workhorse Computing
 
Ruby HTTP clients comparison
Hiroshi Nakamura
 
An Introduction to Windows PowerShell
Dale Lane
 
Remedie: Building a desktop app with HTTP::Engine, SQLite and jQuery
Tatsuhiko Miyagawa
 
Choosing a Javascript Framework
All Things Open
 
Writing Pluggable Software
Tatsuhiko Miyagawa
 
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
Using Websockets with Play!
Andrew Conner
 
Tornado Web Server Internals
Praveen Gollakota
 
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
Matthias Noback
 
PowerShell: Automation for everyone
Gavin Barron
 
Tornado web
kurtiss
 
Python, async web frameworks, and MongoDB
emptysquare
 
Making Symofny shine with Varnish - SymfonyCon Madrid 2014
Barel Barelon
 
Rack Middleware
LittleBIGRuby
 
"Swoole: double troubles in c", Alexandr Vronskiy
Fwdays
 
Nodejs Explained with Examples
Gabriele Lana
 
Perlbal Tutorial
Takatsugu Shigeta
 
Servlets
Manav Prasad
 
Microservice Teststrategie mit Symfony2
Per Bernhardt
 
Ad

Similar to Implementing Comet using PHP (20)

PPT
course slides -- powerpoint
webhostingguy
 
PPT
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
PPT
Eugene Andruszczenko: jQuery
Refresh Events
 
PPT
Real-Time Python Web: Gevent and Socket.io
Rick Copeland
 
PPT
Java Servlets
BG Java EE Course
 
PPT
Rapid java backend and api development for mobile devices
ciklum_ods
 
PPT
Ajax to the Moon
davejohnson
 
PDF
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
PPTX
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
PDF
Pushing the Web: Interesting things to Know
n|u - The Open Security Community
 
PPT
En story of cakephp2.0
Hiroki Shimizu
 
PPT
Node.js: CAMTA Presentation
Rob Tweed
 
PPTX
Spring MVC 3 Restful
knight1128
 
PPT
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
ODP
Web program-peformance-optimization
xiaojueqq12345
 
PPTX
Ruby C10K: High Performance Networking - RubyKaigi '09
Ilya Grigorik
 
PDF
Presto anatomy
Dongmin Yu
 
PDF
[245] presto 내부구조 파헤치기
NAVER D2
 
ODP
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
ODP
Servlets
ramesh kumar
 
course slides -- powerpoint
webhostingguy
 
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
Eugene Andruszczenko: jQuery
Refresh Events
 
Real-Time Python Web: Gevent and Socket.io
Rick Copeland
 
Java Servlets
BG Java EE Course
 
Rapid java backend and api development for mobile devices
ciklum_ods
 
Ajax to the Moon
davejohnson
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Andy McKay
 
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
Pushing the Web: Interesting things to Know
n|u - The Open Security Community
 
En story of cakephp2.0
Hiroki Shimizu
 
Node.js: CAMTA Presentation
Rob Tweed
 
Spring MVC 3 Restful
knight1128
 
Going crazy with Node.JS and CakePHP
Mariano Iglesias
 
Web program-peformance-optimization
xiaojueqq12345
 
Ruby C10K: High Performance Networking - RubyKaigi '09
Ilya Grigorik
 
Presto anatomy
Dongmin Yu
 
[245] presto 내부구조 파헤치기
NAVER D2
 
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Servlets
ramesh kumar
 
Ad

Recently uploaded (20)

PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Software Development Methodologies in 2025
KodekX
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Doc9.....................................
SofiaCollazos
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
This slide provides an overview Technology
mineshkharadi333
 

Implementing Comet using PHP