SSE
This feature requires workerman>=4.0.0
SSE, or Server-sent Events, is a server push technology. Its essence is that after the client sends an HTTP request with the Accept: text/event-stream header, the connection remains open, allowing the server to continuously push data to the client over this connection.
The differences between SSE and WebSocket are:
- SSE only allows server-to-client communication; WebSocket allows bidirectional communication.
- SSE default supports automatic reconnection; WebSocket needs to implement this manually.
- SSE can only transmit UTF-8 text; binary data needs to be encoded into UTF-8 before transmission; WebSocket natively supports the transmission of both UTF-8 and binary data.
- SSE comes with built-in message types; WebSocket needs to be implemented manually.
Example
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)
{
// If the Accept header is text/event-stream, then it's an SSE request
if ($request->header('accept') === 'text/event-stream') {
// First, send a response with a Content-Type: text/event-stream header
$connection->send(new Response(200, ['Content-Type' => 'text/event-stream'], "\r\n"));
// Periodically push data to the client
$timer_id = Timer::add(2, function () use ($connection, &$timer_id) {
// When the connection is closed, delete the timer to avoid memory leaks due to accumulating timers
if ($connection->getStatus() !== TcpConnection::STATUS_ESTABLISHED) {
Timer::del($timer_id);
return;
}
// Send a message event, carrying the data 'hello'; the message id can be omitted
$connection->send(new ServerSentEvents(['event' => 'message', 'data' => 'hello', 'id'=>1]));
});
return;
}
$connection->send('ok');
};
// Run the worker
Worker::runAll();
Client-side JavaScript code
var source = new EventSource('http://127.0.0.1:8080');
source.addEventListener('message', function (event) {
var data = event.data;
console.log(data); // Output hello
}, false);