Server-Sent Events with multiple users

前端 未结 1 1876

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. W

相关标签:
1条回答
  • 2021-01-06 20:55

    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.

    0 讨论(0)
提交回复
热议问题