Server events with multiple users

I’m trying to write a chat program with the new Server-Sent Events API, but I’m having trouble figuring out how to send different events to different users. With all the code coming from a single PHP file, I'm not sure if the best way is to send only specific events to each user. Any help you can give would be greatly appreciated. (I work in PHP and Javascript)

+3
source share
1 answer

Let's say your sender.php code (one php file)

echo "event: ping\n";
$msg1="This is first user";
echo 'data: {"msg": "' . $msg1 . '"}';
echo "\n\n";

echo "event: notify\n";
$msg2="This is second user";
echo 'data: {"msg": "' . $msg2 . '"}';
echo "\n\n";

The first javascript code for the user will look like this

var evtSource = new EventSource("sender.php");
evtSource.addEventListener("ping", function(e) {
var obj = JSON.parse(e.data);
var r_msg = obj.msg;

javascript

var evtSource = new EventSource("sender.php");
evtSource.addEventListener("notify", function(e) {
var obj = JSON.parse(e.data);
var r_msg = obj.msg;

, , . , ping, , , . , .

, .

+4

All Articles