Search code examples
javascriptphphtmlserver-sent-events

Server-Sent Events with multiple users


I'm attempting to write a chat program with the new Server-Sent Events API, however, I've been having trouble figuring out how to send different users different events. With all the code occurring out of one PHP file, I'm unsure the best way to send only certain events to each user. Any help you can give would be greatly appreciated. (I'm working in PHP and Javascript)


Solution

  • Lets say the following is 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";
    

    First user's javascript code will be as follows

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

    and the second user's javascript code will be as follows

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

    Explanation of code is

    You can assign a unique event name to every user and then from sender you just send the data to that event name of that particular user whichever u want. In above code user one will get the messages sent to ping event only and same with second user, it will get messages sent to notify event. In the code above the event name and messages are static but you can make it dynamic as per your requirement.

    Hope this will help you out.