【发布时间】:2017-02-20 17:46:31
【问题描述】:
我正在制作关于空气质量监测系统的大学项目,其中数据(比如一些整数值)必须从传感单元获取到网页。
我想要什么
这个 url http://localhost/AQProject/recordupdate.php?val=2 调用的脚本是否更新了显示内容的网页。现在我知道我可以将该数据保存在数据库中并每两秒运行一次基于 ajax 的查询以检查更新,但我希望该更新由服务器推送。
我做了什么:
我试过Server sent events。这是我尝试过的
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if($_SERVER["REQUEST_METHOD"]=="GET")
{
if(empty($_GET["val"])) die ("Empty Value from source");
else
{
$v = $_GET['val'];
echo "data: The Pollution stub value is {$v}".PHP_EOL;
ob_flush();
flush();
}
}?>
而且html有脚本
<script>
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("recordupdate.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data +
"<br>";
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
现在,我已经弄清楚了(如果我错了,请纠正我)它不会起作用,因为当另一个客户端(传感单元)调用 recordupdate.php 时,它的脚本实例与网页调用的脚本实例不同客户。
有没有可能使用server sent events 做到这一点的方法?或者我绝对需要深入研究 websockets、node.js 等。在此先感谢
【问题讨论】:
标签: javascript php node.js websocket server-sent-events