NAME

Hypersonic::SSE - Server-Sent Events streaming interface

SYNOPSIS

$app->get('/events' => sub {
    my ($req, $stream) = @_;

    my $sse = Hypersonic::SSE->new($stream);

    $sse->event(
        type => 'message',
        data => 'Hello World!',
    );

    $sse->event(
        type => 'update',
        data => '{"count": 42}',
        id   => '123',
    );

    $sse->close();
}, { streaming => 1 });

DESCRIPTION

Hypersonic::SSE provides a high-level API for sending Server-Sent Events. It wraps a Hypersonic::Stream object and handles SSE-specific formatting, headers, and keepalives.

CLIENT EXAMPLE

JavaScript:

const events = new EventSource('/events');

events.onmessage = (e) => {
    console.log('Message:', e.data);
};

events.addEventListener('update', (e) => {
    console.log('Update:', JSON.parse(e.data));
    console.log('Event ID:', e.lastEventId);
});

events.onerror = (e) => {
    if (e.target.readyState === EventSource.CLOSED) {
        console.log('Connection closed');
    } else {
        console.log('Error, will auto-reconnect');
    }
};

RECONNECTION

The browser automatically reconnects when the connection drops. Use the id field to enable resumption:

$app->get('/events' => sub {
    my ($req, $stream) = @_;
    
    my $last_id = $req->header('Last-Event-ID') // 0;
    my $sse = Hypersonic::SSE->new($stream);
    
    for my $id (($last_id + 1) .. 100) {
        $sse->event(
            type => 'update',
            data => "Event $id",
            id   => $id,
        );
    }
    
    $sse->close();
}, { streaming => 1 });

SEE ALSO

Hypersonic::Stream, Hypersonic::Protocol::SSE

AUTHOR

Hypersonic Contributors