服务器发送事件读取Json和更新客户端

时间:2017-01-20 17:59:07

标签: javascript php codeigniter server-sent-events

目前我正在将我的客户端解决方案更新为SSE。它基于Codeigniter和客户端使用javascript。我是SSE的新手。我在Rest API控制器中完成了以下代码。

function server_sent_events_get()
    {
        while (true) {
            header('Content-Type: text/event-stream');
            header('Cache-Control: no-cache');
            $mac = $this->get('macaddress');
            $scheduleid = $this->get('scheduleid');
            $modifiedon = urldecode($this->get('modifiedon'));

            $device_result = $this->read_devices_xml_json($mac);
            $schedule_result = $this->read_schedules_xml_json($scheduleid, $modifiedon);

            echo "event: schedule_status\n";
            echo "data: " . json_encode($schedule_result) . "\n\n";
            echo "event: device_status\n";
            echo "data: " . json_encode($device_result) . "\n\n";
            sleep(2);
        }
    }

在客户端我有以下javascript

if(typeof(EventSource) !== "undefined") {
   var source = new EventSource("../admin/server/macaddress/000000000002/scheduleid/111/modifiedon/0000-00-00%2000:00:00/format/json");
   source.onopen = function(event){
       document.getElementById("result").innerHTML += "opened<br>";
       // console.log(event);
   };
   source.onmessage = function(event) {
       document.getElementById("result").innerHTML += event.data + "<br>";
       // console.log(event);
   };
   source.onerror = function(event){
       document.getElementById("result").innerHTML += "error<br>";
       // console.log(event);
   };
   source.addEventListener('device_status', function(e) {
    var data = JSON.parse(e.data);
    console.log("device_status");
    console.log(data);
   }, false);
   source.addEventListener('schedule_status', function(e) {
    var data = JSON.parse(e.data);
    console.log("schedule_status");
    console.log(data);
   }, false);
} else {
   document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}

控制台中没有错误。但我没有得到我需要的东西。我已经看到它每秒只返回device_status。为什么?请检查我的附件。

Console log 基本上,我有两个XML文件。一个用于设备,一个用于计划。在私有函数中,我正在读取XML文件并将值推送到客户端。在哪里/我错过了什么?请告诉我。

1 个答案:

答案 0 :(得分:0)

我在谷歌墙上打破我的大脑后,在很多文章的帮助下。我已解决了以下问题。希望这对某人有所帮助。

服务器端脚本

function server_sent_events_get()
    {
        ob_start();//must put ob_start if you're using framework. Otherwise there will be a security notice error
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache');
        while (true) {
            $array = array('updates' => intval(false));
            echo "id:" . uniqid() . PHP_EOL;
            $mac = $this->get('macaddress');
            $scheduleid = $this->get('scheduleid');
            $modifiedon = urldecode($this->get('modifiedon'));
            $device_result = $this->read_devices_xml_json($mac);
            $schedule_result = $this->read_schedules_xml_json($scheduleid, $modifiedon);
            if ($device_result['device_status']) {
                echo "event: device_status\n";
                $this->curl_generates_function('device');
                $array = array('updates' => intval(true), 'trigger' => 'device_status', 'event_status' => intval(true));
            } elseif ($schedule_result['schedule_status']) {
                echo "event: schedule_status\n";
                $this->curl_generates_function('schedule');
                $array = array('updates' => intval(true), 'trigger' => 'schedule_status', 'event_status' => intval(true));
            }
            echo "data:" . json_encode($array) . "\n\n";
            ob_flush();
            flush();
            sleep(1);
        }
    }

客户端脚本

function checkingUpdates() {
    console.log("checkingUpdates :: start");
    if (typeof(EventSource) !== "undefined") {
        var source = new EventSource("../admin/server/macaddress/000000000002/scheduleid/111/modifiedon/0000-00-00%2000:00:00/format/json");
        source.onopen = function (event) {
            console.log("checkingUpdates :: EventSource - Open Connection");
        };
        source.addEventListener('device_status', function (event) {
            source.close();
            console.log("checkingUpdates :: EventSource device_status - Close Connection");
            parent.location.reload();
        }, false);

        source.addEventListener('schedule_status', function (event) {
            source.close();
            console.log("checkingUpdates :: EventSource schedule_status - Close Connection");
            top.DataManager.getScheduleByGroupId();
        }, false);

        source.onerror = function (event) {
            console.log("checkingUpdates :: EventSource - Error Connection");
        };
    } else {
        console.log("checkingUpdates :: EventSource - Not Working");
        top.SCHEDULE_TICKER = setInterval(function () {
            top.DataManager.checkScheduleUpdates();
            console.log("checkScheduleUpdates :: Mannual Checking Checked");
        }, top.INTERVAL_UPDATE);
        top.DEVICE_TICKER = setInterval(function () {
            top.DataManager.checkDeviceStatus();
            console.log("checkDeviceStatus :: Mannual Checking Checked");
        }, top.INTERVAL_UPDATE);
    }
    console.log("checkingUpdates :: end");
}

如果答案不合适,请不要犹豫,添加评论/答案。

谢谢!快乐的编码!