7 Star 43 Fork 6

Xie Biao / php-sse

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
MIT

PHP SSE: Server-sent Events

A simple and efficient library implemented HTML5's server-sent events by PHP, is used to real-time push events from server to client, and easier than Websocket, instead of AJAX request.

Requirements

  • PHP 5.4 or later

Installation via Composer(packagist)

composer require "hhxsv5/php-sse:~2.0" -vvv

Usage

Run demo

  • Run PHP webserver
cd examples
php -S 127.0.0.1:9001 -t .
  • Open url http://127.0.0.1:9001/index.html

Demo

Javascript demo

Client: receiving events from the server.

// withCredentials=true: pass the cross-domain cookies to server-side
const source = new EventSource('http://127.0.0.1:9001/sse.php', {withCredentials: true});
source.addEventListener('news', function (event) {
    console.log(event.data);
    // source.close(); // disconnect stream
}, false);

PHP demo

Server: Sending events by pure php.

use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\SSE;
use Hhxsv5\SSE\StopSSEException;

// PHP-FPM SSE Example: push messages to client

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

$callback = function () {
    $id = mt_rand(1, 1000);
    $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
    if (empty($news)) {
        return false; // Return false if no new messages
    }
    $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
    if ($shouldStop) {
        throw new StopSSEException();
    }
    return json_encode(compact('news'));
    // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
    // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
};
(new SSE(new Event($callback, 'news')))->start();

Symfony and Laravel demo

Server: Sending events by Laravel or Symfony.

use Hhxsv5\SSE\SSE;
use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\StopSSEException;

// Action method in controller
public function getNewsStream()
{
    $response = new \Symfony\Component\HttpFoundation\StreamedResponse();
    $response->headers->set('Content-Type', 'text/event-stream');
    $response->headers->set('Cache-Control', 'no-cache');
    $response->headers->set('Connection', 'keep-alive');
    $response->headers->set('X-Accel-Buffering', 'no'); // Nginx: unbuffered responses suitable for Comet and HTTP streaming applications
    $response->setCallback(function () {
        $callback = function () {
            $id = mt_rand(1, 1000);
            $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
            if (empty($news)) {
                return false; // Return false if no new messages
            }
            $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
            if ($shouldStop) {
                throw new StopSSEException();
            }
            return json_encode(compact('news'));
            // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
            // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
        };
        (new SSE(new Event($callback, 'news')))->start();
    });
    return $response;
}

Swoole demo

Server: Sending events by Swoole Coroutine Http Server. Install Swoole 4.5.x: pecl install swoole.

use Hhxsv5\SSE\Event;
use Hhxsv5\SSE\SSESwoole;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
use Hhxsv5\SSE\StopSSEException;

// Swoole SSE Example: push messages to client

$server = new Server('0.0.0.0', 5200);
$server->set([
    'enable_coroutine'   => true,
    'max_coroutine'      => 10000, // worker_num*10000
    'reactor_num'        => swoole_cpu_num() * 2,
    'worker_num'         => swoole_cpu_num() * 2,
    'max_request'        => 100000,
    'buffer_output_size' => 4 * 1024 * 1024, // 4MB
    'log_level'          => SWOOLE_LOG_WARNING,
    'log_file'           => __DIR__ . '/swoole.log',
]);

$server->on('Request', function (Request $request, Response $response) use ($server) {
    $response->header('Access-Control-Allow-Origin', '*');
    $response->header('Content-Type', 'text/event-stream');
    $response->header('Cache-Control', 'no-cache');
    $response->header('Connection', 'keep-alive');
    $response->header('X-Accel-Buffering', 'no');

    $event = new Event(function () {
        $id = mt_rand(1, 1000);
        $news = [['id' => $id, 'title' => 'title ' . $id, 'content' => 'content ' . $id]]; // Get news from database or service.
        if (empty($news)) {
            return false; // Return false if no new messages
        }
        $shouldStop = false; // Stop if something happens or to clear connection, browser will retry
        if ($shouldStop) {
            throw new StopSSEException();
        }
        return json_encode(compact('news'));
        // return ['event' => 'ping', 'data' => 'ping data']; // Custom event temporarily: send ping event
        // return ['id' => uniqid(), 'data' => json_encode(compact('news'))]; // Custom event Id
    }, 'news');
    (new SSESwoole($event, $request, $response))->start();
});
$server->start();

License

MIT

MIT License Copyright (c) 2017 Dave Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

PHP SSE: Server-sent Events,通过 PHP 实现了 HTML5 的服务器发送事件,用于实时从服务器推送事件到客户端,比 WebSocket 更简单。 展开 收起
PHP
MIT
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
PHP
1
https://gitee.com/hhxsv5/php-sse.git
git@gitee.com:hhxsv5/php-sse.git
hhxsv5
php-sse
php-sse
master

搜索帮助