Search code examples
javascriptphpserver-sent-eventsevent-stream

Server Sent Events - Event-Stream - Trigger a PHP server side event?


I have a chat panel using HTML, CSS, jQuery. Set up an event listener with no problems. Set up a text/event-stream php file which can send messages to client with no problems. How do I communicate from client to this server script so that it will broadcast a message to all users who have an event-stream open, upon receipt of new message from any one of the clients? The server should only send an event upon receipt of a new message.

Here is message_sender.php:

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

while (1) {
 if ($newMessage){ //How does $newMessage get filled in an already running script?
  echo "id: 1234\n";
  echo "event: ping\n";
  echo 'data: {"newMessage": "' . $newMessage . '"}';
  echo "\n\n";
 }

 ob_flush();
 flush();
 sleep(1);
}

Here is js:

var evtSource = new EventSource("message_sender.php");

evtSource.onmessage = function(e) {
}

evtSource.addEventListener("ping", function(e) {
 var newElement = document.createElement("li");       
 var obj = JSON.parse(e.data);
 newElement.innerHTML = "ping " + obj.newMessage;
 $('#chat_panel').append(newElement);
}, false);

evtSource.onerror = function(e) {
    alert("EventSource failed.");
};

$('#message_form').submit(function(e){
 e.preventDefault();
 var message = $('#txtb_chat').val();

 $.ajax({
  type: 'POST',
  dataType: 'json',
  data: message,
  url: 'message_processor.php',
  beforeSend: function(){

  },
  success: function(){
   $('#txtb_chat').val("");
  }
 });
 return false;
});

Solution

  • You can use AJAX to send new messages to the server and store messages in a database.

    You can fill $newMessage by querying the shared database.

    You can use id: and Last-Event-Id to track which messages client has seen and query SELECT * FROM chat WHERE id > $last_event_id.