SSE

2019-10-22

html5提供了Server-Sent Events方法,通过服务器发送事件,更新能够自动到达。

使用示例:

if (typeof (EventSource) !== "undefined") {
    var source = new EventSource("server.php");
    source.onopen = function () {
        console.log("Connection to server opened.");
    };
    source.onmessage = function (event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
    source.onerror = function () {
        console.log("EventSource failed.");
    };
}
else {
    document.getElementById("result").innerHTML = "抱歉,你的浏览器不支持 server-sent 事件...";
}

服务端:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

date_default_timezone_set('PRC');

$i = 0;

while (++$i < 100) {
    echo "id: " . $i . "\tdate: " . date('c') . ";\n\n";
    ob_flush();
    flush();
    sleep(1);
}

SSE与MQTT对接

https://github.com/CloudMQTT/mqtt-sse