2

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;
});

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the response. I was hoping there was a way to handle this in memory instead of using a mysql db. I suppose there may not be a better way though than a db.
@carter You can use in-memory database like Redis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.