[英]HTML5 Server-Sent Event
I am trying to build real time app using SSE. 我正在尝试使用SSE构建实时应用程序。 But it doesn't work when I think I write everything in right way.
但是,当我认为我以正确的方式编写所有内容时,它是行不通的。 Please help me with this problem.
请帮我解决这个问题。 I know websockets is better than SSE but I in beginning Here is my index.html code
我知道websockets比SSE更好,但是我一开始就在这里,这是我的index.html代码
<!DOCTYPE html> <html> <head> <title>Using SSE(Server-sent event)</title> <meta charset="utf-8"> </head> <body> <h1>Getting server updates</h1> <div id="result"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("getdata.php"); source.onmessage = function(event) { console.log(JSON.parse(event.data)); }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html>
and this is getdata.php page 这是getdata.php页面
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
$obj = $pdo->query("select * from users");
$arr = $obj->fetchAll();
echo "data: ".json_encode($arr);
flush();
?>
when i used 当我用
source.onerror = function(er){
console.log(er);
}
I got this 我懂了
error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 5152.813223, cancelBubble: false, originalTarget: EventSource }
I tried comment code in html console.log(JSON.parse(event.data)); 我在html console.log(JSON.parse(event.data))中尝试了注释代码; but it doesn't work too.
但它也不起作用。
Please help understanding how SSE works and what is the wrong in my code? 请帮助理解SSE的工作原理,我的代码有什么问题?
Thanks in advance. 提前致谢。
I found out it why it doesn't work. 我发现了为什么它不起作用。 I added \\n\\n
我加了\\ n \\ n
echo "data: ".json_encode($arr);
so it looks like this 所以看起来像这样
echo "data: ".json.encode($arr)."\n\n";
I hope it helps 希望对您有所帮助
EDIT (just to leave in accordance for future viewers) 编辑 (只是为了将来的观众而离开)
check (then press F12 in your browser and check "Console" - it's working for me in Firefox and Chrome) 检查 (然后在浏览器中按F12并检查“控制台”-它在Firefox和Chrome中对我有效)
See the code exactly as it are on that server: 完全按照该服务器上的代码查看代码:
sse.html sse.html
<!DOCTYPE html>
<html>
<head>
<title>Using SSE(Server-sent event)</title>
<meta charset="utf-8">
</head>
<body>
<h1>Getting server updates</h1>
<div id="result"></div>
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("getdata.php");
source.onmessage = function(event) {
console.log(JSON.parse(event.data));
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
getdata.php (still mysql, not msqli or PDO because of an old server) getdata.php(由于是旧服务器,仍然是mysql,而不是msqli或PDO)
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
include("../../admin2/config.inc.php");
connect_db();
$query = mysql_query( "select * from ttbb" ) or die( mysql_error() );
$arr = mysql_fetch_object( $query );
echo "data: ".json_encode($arr)."\n\n";
flush();
?>
Firstly, and most importantly, the PHP script should be running forever, not doing one query and then dying. 首先,也是最重要的是,PHP脚本应该永远运行,而不是执行一个查询然后死亡。 (If that was your intention, then you don't need a streaming solution, and should just use AJAX.)
(如果这是您的意图,那么您就不需要流解决方案,而应该使用AJAX。)
Second, you need two LFs after each data::
. 其次,每个
data::
之后需要两个LF data::
。 And you (probably) also need ob_flush()
in addition to just flush()
. 而且(可能)除了
flush()
之外,您还可能需要ob_flush()
flush()
。 With all three changes it looks like this: 经过这三个更改,看起来像这样:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
while(true){ //Deliberate infinite loop
$obj = $pdo->query("select * from users");
$arr = $obj->fetchAll();
echo "data: ".json_encode($arr)."\n\n";
@ob_flush();@flush(); //Use @ to suppress v.rare but meaningless errors
sleep(1); //Poll the database every second.
}
?> ?>
I've set it (the server) to poll the local database every second. 我已将其(服务器)设置为每秒轮询本地数据库。 You should adjust this based on the balance of server load against target latency.
您应该根据服务器负载与目标延迟之间的平衡来调整此值。
IMPORTANT: This will send all user data to all clients, every second. 重要说明:这将每秒将所有用户数据发送到所有客户端。 You should redesign your SQL query to only fetch users that have changed since your last query.
您应该重新设计SQL查询,以仅提取自上次查询以来已更改的用户。 And then re-design the front-end to be given all users on the first call, and then after that just the changes.
然后重新设计前端,以便在第一次呼叫时为所有用户提供服务,然后再进行更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.