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

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
 

Similar to Implementing Comet using PHP (20)

PPT
Realtime Communication Techniques with PHP
WaterSpout
 
ODP
Comet / WebSocket Web Applications
Codemotion
 
PPTX
Comet Server Push Over Web
Morgan Cheng
 
PPTX
Taking a Quantum Leap with Html 5 WebSocket
Shahriar Hyder
 
PDF
Going Live! with Comet
Simon Willison
 
PPTX
Reverse ajax in 2014
Nenad Pecanac
 
PPTX
Behind the scenes of Real-Time Notifications
Guillermo Mansilla
 
PPTX
Comet: an Overview and a New Solution Called Jabbify
Brian Moschel
 
PDF
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Brian Sam-Bodden
 
PDF
Time for Comet?
Simon Willison
 
PDF
Comet: Making The Web a 2-Way Medium
Joe Walker
 
PPT
Comet: by pushing server data, we push the web forward
NOLOH LLC.
 
PPT
HTTP Server Push Techniques
Folio3 Software
 
PDF
wa-cometjava-pdf
Hiroshi Ono
 
PDF
Server-Sent Events (real-time HTTP push for HTML5 browsers)
yay w00t
 
ZIP
robrighter's Node.js presentation for DevChatt
robrighter
 
PPTX
Real time web: is there a life without socket.io and node.js?
Eduard Trayan
 
PDF
Comet from JavaOne 2008
Joe Walker
 
PPT
Get Real: Adventures in realtime web apps
daviddemello
 
PPT
Web-Socket
Pankaj Kumar Sharma
 
Realtime Communication Techniques with PHP
WaterSpout
 
Comet / WebSocket Web Applications
Codemotion
 
Comet Server Push Over Web
Morgan Cheng
 
Taking a Quantum Leap with Html 5 WebSocket
Shahriar Hyder
 
Going Live! with Comet
Simon Willison
 
Reverse ajax in 2014
Nenad Pecanac
 
Behind the scenes of Real-Time Notifications
Guillermo Mansilla
 
Comet: an Overview and a New Solution Called Jabbify
Brian Moschel
 
Server-Side Push: Comet, Web Sockets come of age (OSCON 2013)
Brian Sam-Bodden
 
Time for Comet?
Simon Willison
 
Comet: Making The Web a 2-Way Medium
Joe Walker
 
Comet: by pushing server data, we push the web forward
NOLOH LLC.
 
HTTP Server Push Techniques
Folio3 Software
 
wa-cometjava-pdf
Hiroshi Ono
 
Server-Sent Events (real-time HTTP push for HTML5 browsers)
yay w00t
 
robrighter's Node.js presentation for DevChatt
robrighter
 
Real time web: is there a life without socket.io and node.js?
Eduard Trayan
 
Comet from JavaOne 2008
Joe Walker
 
Get Real: Adventures in realtime web apps
daviddemello
 
Ad

Recently uploaded (20)

PDF
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PPTX
Wondershare Filmora Crack Free Download 2025
josanj305
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Understanding The True Cost of DynamoDB Webinar
ScyllaDB
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
Practical Applications of AI in Local Government
OnBoard
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
CapCut Pro PC Crack Latest Version Free Free
josanj305
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Kubernetes - Architecture & Components.pdf
geethak285
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Wondershare Filmora Crack Free Download 2025
josanj305
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
Ad

Implementing Comet using PHP