Server-Sent Events with multiple users
Asked Answered
S

1

3

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)

Shawnna answered 19/4, 2013 at 3:34 Comment(5)
What kind of thing do you want to filter who gets what? Without code at all, we can't helpClarkia
I've just been working on some tests so that I understand the API before I start working on the chat program. I need to control who receives notification when a new message is received by the server. I'm sure this is basic, but I'm pretty confused...Shawnna
Well, if it's a chat program, you must have some implementation of chat "rooms" and which room a user is in. From that, you should be able to send messages to users in the chat room.Clarkia
Yes, but I'm wondering how you differentiate between those rooms (I don't want to write a different set of code for each one)Shawnna
Realetd quesiton #15713580Alpha
M
3

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.

Meath answered 24/4, 2013 at 5:59 Comment(2)
And if several clients want to receive the same event? And, can clients "unsubscribe"? (great answer, though +1)Alpha
The events are still sent to everyone and only filtered client side, so all messages are basically public and everyone incur the cost of receiving all the events. The proposed solution will work, but not secure or scalable.Ciscaucasia

© 2022 - 2024 — McMap. All rights reserved.