具有多个用户的服务器发送事件 [英] Server-Sent Events with multiple users

查看:85
本文介绍了具有多个用户的服务器发送事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的Server-Sent Events API编写聊天程序,但是,我一直在弄清楚如何向不同的用户发送不同的事件。由于所有代码都来自一个PHP文件,我不确定向每个用户发送特定事件的最佳方式。您将给予的任何帮助将不胜感激。 (我正在使用PHP和Javascript)

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)

推荐答案

让我们说以下是你的sender.php代码(一个php文件)

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";

第一位用户的javascript代码如下:

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;

,第二个用户的javascript代码如下:

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;

代码说明是

您可以为每个用户分配一个唯一的事件名称,然后从发件人只需将数据发送到该特定用户的事件名称即可。在上面的代码中,用户将得到一个发送到ping事件的消息和第二个用户一样,它会发送消息发送到notify事件。在上面的代码中,事件名称和消息是静态的,但你可以根据你的要求使它动态化。

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.

希望这会帮助你。

这篇关于具有多个用户的服务器发送事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆