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

Developing Large Web Applications

Developing Large Web Applications

Kyle Loudon / Yahoo Press / 2010-3-15 / USD 34.99

As web applications grow, so do the challenges. These applications need to live up to demanding performance requirements, and be reliable around the clock every day of the year. And they need to withs......一起来看看 《Developing Large Web Applications》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码