Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send notification from server to client on server event

How can I send a message from server to client with PHP, avoiding extraneous Ajax calls.

Here is the idea:

  1. User: Alice makes a change which gets sent to the server.

  2. 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?

like image 234
user3765372 Avatar asked Jun 22 '14 19:06

user3765372


People also ask

How do I push client/server notifications?

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.

What is SSE notification?

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.

How does server-sent events work?

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.


1 Answers

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.

like image 54
secretformula Avatar answered Oct 05 '22 04:10

secretformula