服務(wù)端給消息里加個(gè)時(shí)間
客戶端里可見本次消息時(shí)間和上次消息時(shí)間
消息打印結(jié)果如圖
客戶打印出來的第一條消息里lastEventId輸出的時(shí)間與服務(wù)器發(fā)送的第一條消息的時(shí)間相同,也就是說客戶端只打印了服務(wù)器發(fā)送過來的第二條消息,嗯。。。我有點(diǎn)整不明白了
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\ServerSentEvents;
use Workerman\Protocols\Http\Response;
use Workerman\Timer;
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('http://0.0.0.0:8080');
$worker->onMessage = function(TcpConnection $connection, Request $request)
{
// 如果Accept頭是text/event-stream則說明是SSE請求
if ($request->header('accept') === 'text/event-stream') {
// 首先發(fā)送一個(gè) Content-Type: text/event-stream 頭的響應(yīng)
$connection->send(new Response(200, ['Content-Type' => 'text/event-stream']));
// 定時(shí)向客戶端推送數(shù)據(jù)
$timer_id = Timer::add(2, function () use ($connection, &$timer_id){
static $id = 0;
// 連接關(guān)閉的時(shí)候要將定時(shí)器刪除,避免定時(shí)器不斷累積導(dǎo)致內(nèi)存泄漏
if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($timer_id);
return;
}
// 發(fā)送message事件,事件攜帶的數(shù)據(jù)為hello,消息id可以不傳
$connection->send(new ServerSentEvents(['event' => 'message', 'data' => 'hello', 'id'=>$id++]));
});
return;
}
$connection->send("<script>
var source = new EventSource('http://127.0.0.1:8080');
source.addEventListener('message', function (event) {
var data = event.data;
console.log(event); // 輸出 hello
}, false);
</script>");
};
// 運(yùn)行worker
Worker::runAll();
id從0開始輸出的,沒問題
這個(gè)id對應(yīng)的是event.lastEventId,但lastEvent客戶端并沒有收到,比如改成這樣比對一下服務(wù)端發(fā)送的內(nèi)容和客戶端打印出的內(nèi)容
$timer_id = Timer::add(2, function () use ($connection, &$timer_id){
static $id = 0;
// 連接關(guān)閉的時(shí)候要將定時(shí)器刪除,避免定時(shí)器不斷累積導(dǎo)致內(nèi)存泄漏
if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($timer_id);
return;
}
// 發(fā)送message事件,事件攜帶的數(shù)據(jù)為hello,消息id可以不傳
$data='data of event with ID '.$id;
echo "I'm about send msgid:$id".PHP_EOL;
$connection->send(new ServerSentEvents(['event' => 'message', 'data' => $data, 'id'=>$id]));
$id++;
});
是不是服務(wù)端發(fā)送的數(shù)據(jù),第一次客戶端收不到;客戶端第二次收到的數(shù)據(jù)中l(wèi)astEventId卻可以獲取到服務(wù)端第一次發(fā)送的id