H5 Server-Sent 事件 - 單向消息傳遞

雖然之前知道這個技術,可是一直沒去了解過,今天在這裏記錄一下,先看W3school說的php

clipboard.png
這意味着能夠作一些簡單的消息推送
下面是個人代碼:
html頁面html

<div class="layui-wz" style="width: 100%;text-align: center;">
    <input type="hidden" class="paging">
    <div id="test">倒計時</div>
    <button id="open" type = "button" class="layui-btn layui-btn-radius">開啓簽到</button>
    <button id="close" type = "button" class="layui-btn layui-btn-radius">結束簽到</button>
</div>
<div class="result">
    <table class="handle_message">
        <tr></tr>
    </table>
</div>

js代碼:html5

var source,message,timer;
/**
 * 開啓簽到 - 開始檢查服務端是否有更新
 */
$("#open").click(function () {
    countdown();
    if(typeof(EventSource)!=="undefined") {
        source = new EventSource("http://10.3.140.139:8082/index/test/getuser");
        source.onmessage=function(event)//接收到消息
        {
            message = event.data;
            var len = message.length;
            if (len > 0) {
                message = JSON.parse(message);
                $(".handle_message tr").append(code(message['head_pic'],message['username']));
            }
        };
    } else {
        layer.msg('抱歉,你的瀏覽器不支持 server-sent 事件...');
    }
});

/**
 * 關閉監聽
 */
$("#close").click(function () {
    cz_close();
});
/**
 * 關閉監聽操做
 */
function cz_close() {
    timer = $(".paging").val();
    clearTimeout(timer);
    $('#test').html('簽到結束');
    source.close();
    $.post("http://10.3.140.139:8082/index/test/clearcache");
    layer.msg('中止監聽服務器更新');
}

/**
 * 追加代碼
 * @returns {string}
 */
function code(pic,name) {
    var code = '<td>' +
        '<img src="'+ pic +'" alt="http://tva2.sinaimg.cn/large/005ucgoIly1g3iiq7a591j30jg0jgwl0.jpg" class="layui-nav-img">' +
        '<p style="margin-left: 38px;margin-top: 8px;"><span>'+ name +'</span></p>' +
        '</td>';
    return code;
}

/**
 * 倒計時
 */
function countdown() {
    layui.use('util', function(){
        var util = layui.util,
        serverTime = new Date().getTime(),
        endTime = serverTime + (2 * (60 * 1000));
        util.countdown(endTime, serverTime, function(date, serverTime, timer){
            $(".paging").val(timer);
            var str = date[2] + '分' + date[3] + '秒';
            if (date[0] == 0 && date[1] == 0 && date[2] == 0 && date[3] == 0) {
                clearTimeout(timer);//清除定時器
                cz_close();
            }else {
                $('#test').html('剩餘時間:'+ str);
            }
        });
    });
}

php代碼:json

/**
     * @return mixed
     * 學生端簽到頁面
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * @return mixed
     * 教師端開啓簽到頁面
     */
    public function demo()
    {
        return $this->fetch();
    }

    /**
     * 將簽到的學生加入緩存
     */
    public function post()
    {
        if ($_POST) {
            $img = self::curlInfo();
            $_POST['head_pic'] = $img;
            $info = json_encode($_POST);
            Cache::set('user_info',$info);
        }
    }

    /**
     * 緩存取出用戶
     */
    public function getUser ()
    {
        //取出並清除當前緩存
        $info = Cache::pull('user_info');
        ////服務端事件標準規定(將MIME類型設爲text/event-stream)
        header('Content-Type: text/event-stream');
        ////告訴Web服務器關閉Web緩存
        header('Cache-Control: no-cache');
        echo "data:{$info}\n\n";
        //當即發送數據(而不是先緩衝起來,等到PHP代碼執行完畢再發送)
        flush();
    }

    /**
     * 清除緩存
     */
    public function clearCache ()
    {
        Cache::clear();
    }

    /**
     * @return mixed
     * 獲取用戶隨機頭像
     */
    protected function curlInfo ()
    {
        $url = 'https://api.66mz8.com/api/rand.pic.php?type=%E4%B8%AA%E6%80%A7&return=json';
        $curl = curl_init();//初始化CURL句柄
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl,CURLOPT_HTTPGET,true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        $info = json_decode($output,true);
        $img = $info['imgurl'];
        return $img;
    }

參考連接:http://www.w3school.com.cn/ht...
http://www.hangge.com/blog/ca...api

相關文章
相關標籤/搜索