Search code examples
phphtmlsocketsbroadcastserver-sent-events

Broadcasting messages with Server-Sent events


I want to implement a simple Server-Sent events app where clients listen to a php file like this

<script src="eventsource.js"></script>
<script>
  var es = new EventSource('../sse.php');

  es.onmessage = function (event) {
    var data = JSON.parse(event.data);
    console.log('msg: ' + event.data);
  };

  es.onopen = function () {
    console.log('connected');
  }
</script>

but then i need to be able to broadcast a message and every connected client gets it simultaneously.

The php file will be triggered by another request and it will "echo" some SSE data to all clients.

Is this possible? Is there another route i can take?

Thank you in advance


Solution

  • PHP is not going to be great for this. If you have lots of clients waiting for this event, you're going to require an instance of the PHP interpreter (and probably an apache thread) for each client that's waiting.

    What you might consider doing is having an event driven server handle this. Node.JS and Tornado (Python) are two environments I've used in the past in similar circumstances. If you use Node.js, you may want to look into socket.io for this -- it doesn't use Server Sent Events, but would make what you want very simple.

    You could have two webservers side by side, your current server (I'm assuming Apache) and one written by you to handle the clients waiting for updates. Whenever the PHP server wants to send a message to waiting clients, the PHP server notifies the other server (AMQP, ZeroMQ, redis Pub/Sub or a simple HTTP request on a non-public interface would all be good choices), and that server passes on the message to any waiting clients.

    You can see a very simple version of what I'm talking about using node.js + socket.io (Which could easily be replaced by SSE) on github.