PHP 实现 HTML5 的服务器发送事件 PHP SSE

码农软件 · 软件分类 · 网络工具包 · 2019-02-24 16:14:19

软件介绍

PHP SSE: Server-sent Events,一个简单有效的库,通过 PHP 实现了 HTML5 的服务器发送事件,用于实时从服务器推送事件到客户端,比 Websocket 更容易。

要求:PHP 5.4 or later

示例代码

Javascript demo

Client: receiving events from the server

//withCredentials=true: pass the cross-domain cookies to server-side
var source = new EventSource("http://127.0.0.1:9001/push.php", {withCredentials:true});
source.addEventListener("new-msgs", function(event){
    console.log(event.data);//get data
}, false);

PHP demo

Server: sending events from the server by pure php

include './vendor/autoload.php';

use Hhxsv5\SSE\SSE;
use Hhxsv5\SSE\Update;

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');//Nginx: unbuffered responses suitable for Comet and HTTP streaming applications

(new SSE())->start(new Update(function () {
    $id = mt_rand(1, 1000);
    $newMsgs = [
        [
            'id'      => $id,
            'title'   => 'title' . $id,
            'content' => 'content' . $id,
        ],
    ];//get data from database or servcie.
    if (!empty($newMsgs)) {
        return json_encode(['newMsgs' => $newMsgs]);
    }
    return false;//return false if no new messages
}), 'new-msgs');

本文地址:https://www.codercto.com/soft/d/41.html

程序化广告实战

程序化广告实战

吴俊 / 机械工业出版社 / 2017-8-15 / 79.00元

中国程序化广告领域领袖级专家,私有化程序购买领域的布道者的一线实战笔记,宋星等近20位专家联袂推荐。从业务和技术双重视角系统讲解程序化广告的理论、知识、实践方法和关键要点。一起来看看 《程序化广告实战》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试