要使用 PHP 构建基于 Event-Stream 的实时应用,您需要遵循以下步骤:
composer require swoole/swoole
<?php
require_once 'vendor/autoload.php';
use Swoole\Http\Server;
use Swoole\Http\Request;
use Swoole\Http\Response;
$server = new Server("0.0.0.0", 8080);
$server->on('request', function (Request $request, Response $response) {
$response->header('Content-Type', 'text/event-stream');
$response->header('Cache-Control', 'no-cache');
$response->header('Connection', 'keep-alive');
$response->header('Transfer-Encoding', 'chunked');
// 在这里处理您的实时应用逻辑
});
$server->start();
function sendEvent(Response $response, string $event, string $data)
{
$response->write("event: {$event}\n");
$response->write("data: {$data}\n\n");
}
EventSource
对象连接到服务器并监听事件。以下是一个示例代码:const eventSource = new EventSource('http://localhost:8080');
eventSource.addEventListener('message', (event) => {
console.log('Received event:', event.data);
});
eventSource.addEventListener('error', (error) => {
console.error('Error:', error);
});
php server.php
现在,您已经成功地使用 PHP 构建了一个基于 Event-Stream 的实时应用。您可以根据需要修改服务器端和客户端代码以满足您的实际需求。