H5-ServerSent-事件-单向消息传递

21次阅读

共计 2478 个字符,预计需要花费 7 分钟才能阅读完成。

虽然以前知道这个技术,但是一直没去了解过,今天在这里记录一下,先看 W3school 说的


这意味着可以做一些简单的消息推送
下面是我的代码:
html 页面

<div class="layui-wz" style="width: 100%;text-align: center;">
    <button id="open" type = "button" class="layui-btn layui-btn-radius" style="width: 9%;line-height: 10px;height: 167px"> 开启签到 </button>
    <button id="close" type = "button" class="layui-btn layui-btn-radius" style="width: 9%;line-height: 10px;height: 167px"> 结束签到 </button>
</div>
<div class="result">
    <table class="handle_message">
        <tr></tr>
    </table>
</div>

js 代码:

var source,message;
/**
 * 开启签到 - 开始检查服务端是否有更新
 */
$("#open").click(function () {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 () {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;
}

php 代码:

/**
     * @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…

正文完
 0