How can I send a message from server to client with PHP, avoiding extraneous Ajax calls.
Here is the idea:
User: Alice makes a change which gets sent to the server.
The Server then checks to see which users are not up to date, and if not calls some code to send the information pertaining to the change to Bob (who is not up to date in this case).
How do I send Bob the message?
At a high-level, the key steps for implementing push notifications are: Adding client logic to ask the user for permission to send push notifications, and then sending client identifier information to your server for storage in a database. Adding server logic to push messages to client devices.
SSE definition states that it is an http standard that allows a web application to handle a unidirectional event stream and receive updates whenever the server emits data. In simple terms, it is a mechanism for unidirectional event streaming.
So what are Server-Sent Events? A client subscribes to a “stream” from a server and the server will send messages (“event-stream”) to the client until the server or the client closes the stream. It is up to the server to decide when and what to send the client, for instance, as soon as data changes.
You can use Server Sent Events.
These are the often over looked cousin of websockets that are lighter weight and one way. They essentially allow the client to wait for a message from the server (which you can then respond to via a different channel such as AJAX)
Example Client Code:
var source = new EventSource('/newFile');
source.addEventListener('message', function(e) {
// Use AJAX and pull new file here
}, false);
Unfortuantely it seems (of course) that there is no IE support. One could use a library such as EventSource HQ to support cross browser server sent events. It will abstract away needing to handle the devil's browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With