I have tried reading some articles, but I am not very clear on the concepts yet.
Would someone like to take a shot at explaining to me what these technologies are:
One thing that I came across every time was, the server keeps a connection open and pushes data to the client. How is the connection kept open, and how does the client get the pushed data? (How does the client use the data, maybe some code might help?)
Now, which one of them should I use for a real-time app. I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP?
This question is related to
php
websocket
comet
long-polling
server-sent-events
In the examples below the client is the browser and the server is the webserver hosting the website.
Before you can understand these technologies, you have to understand classic HTTP web traffic first.
The server sends an event to the client when there's new information available.
The server and the client can now send each other messages when new data (on either side) is available.
Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.
Now, which one of them should I use for a realtime app (that I need to code). I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP ?
You can use PHP with WebSockets, check out Ratchet.
You can easily use Node.JS in your web app only for real-time communication. Node.JS is really powerful when it's about WebSockets. Therefore "PHP Notifications via Node.js" would be a great concept.
See this example: Creating a Real-Time Chat App with PHP and Node.js
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
Tieme put a lot of effort into his excellent answer, but I think the core of the OP's question is how these technologies relate to PHP rather than how each technology works.
PHP is the most used language in web development besides the obvious client side HTML, CSS, and Javascript. Yet PHP has 2 major issues when it comes to real-time applications:
libphp5.so
on Linux, php5ts.dll
on Windows, etc) as if it still a CGI processing a GET/POST request. It still executes code as if it just has to build a "page" and then end its life cycle. As a result, it has very little support for multi-thread or event-driven programming (within PHP userspace), making it currently unpractical for real-time, multi-user applications.Note that PHP does have extensions to provide event loops (such as libevent
) and threads (such as pthreads
) in PHP userspace, but very, very, few of the applications use these.
PHP 7 will be a great step to fix these issues as well, and seems very promising as a platform for real-time applications.
Source: Stackoverflow.com