Server

NAME

EventSource::Server - A simple handler to provide Server Sent Events from Raku applications

SYNOPSIS

This sends out an event with the DateTime string every second

use EventSource::Server;
use HTTP::Server::Tiny;

my $supply = Supply.interval(1).map( { EventSource::Server::Event.new(type => 'tick', data => DateTime.now.Str) } );

my &es = EventSource::Server.new(:$supply);

HTTP::Server::Tiny.new(port => 7798).run(&es)

And in some Javascript program somewhere else:


var EventSource = require('eventsource');

var v = new EventSource(' http://127.0.0.1:7798');

v.addEventListener("tick", function(e) {
    console.info(e);

}, false);

See also the examples directory in this distribution.

DESCRIPTION

This provides a simple mechanism for creating a source of Server Sent Events in a HTTP::Server::Tiny server or a Cro application.

The EventSource interface is implemented by most modern web browsers and provides a lightweight alternative to Websockets for those applications where only a uni-directional message is required (for example for notifications.)

METHODS

new

The constructor takes named arguments:

  • supply

A Supply that provides the events, if this is not provided then the events can be emitted onto the EventSource::Server object directly.

  • keepalive

If this adverb is supplied then a 'keep-alive' chunk will be emitted on the stream at the frequency specified by keepalive-frequency (the default is 60 seconds.) The "chunk" is basically a 0 byte followed by CRLF and will not cause an event in the connected client. This may be useful with some clients that periodically reconnect if there is no traffic on the stream, or some reverse proxy that may disconnect after some time with no data.

  • keepalive-frequence

The frequency in seconds of the keepalive chunks if <keepalive> is set. The default is 60.

emit

This emits an event onto the internal supplier to be merged into the out-supply.

out-supply

This returns the Supply of EventSource::Server::Event encoded as a UTF-8 Blob which forms the event stream. This can be passed directly to the content helper of Cro like:

content 'text/event-stream', $e.out-supply;

stop

This calls done on the out-supply. You may need to call this in an application where a client can refresh its view thus causing a new connection to the server, however until the previous supply is done the stream will attempt to write to the now closed connection ( leading to a "Cannot write to a closed socket" error from your application.) This is most useful in an application which uses user session which enables tracking of per-session event streams.

EventSource::Server v0.0.11

A simple handler to provide Server Sent Events from a Raku application

Authors

  • Jonathan Stowe

License

Artistic-2.0

Dependencies

Test Dependencies

Provides

  • EventSource::Server

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.