Plack::App::EventSource - EventSource/SSE for Plack
use Plack::App::EventSource; use Plack::Builder; builder { mount '/events' => Plack::App::EventSource->new( handler_cb => sub { my ($conn, $env) = @_; $conn->push('foo'); # or # $conn->push('foo', 'bar', 'baz'); # or # $conn->push({id => 1, data => 'foo'}); $conn->close; } )->to_app; mount '/' => $app; };
Plack::App::EventSource is an EventSource or Server Sent Events applications. EventSource is an alternative to WebSockets when there is no need for duplex communication. EventSource uses HTTP and is much simpler in implementation. Ideal for website notifications or read only update streams.
This library stays event loop agnostic, which means that you can use it with AnyEvent or POE or even just with a plain forking server.
Plack::App::Eventsource is a subclass of Plack::Component, inheriting all its methods. You should only have to know about the to_app method.
to_app
handler_cb
The main application entry point. It is called with Plack::App::EventSource::Connection and PSGI $env parameters.
$env
handler_cb => sub { my ($conn, $env) = @_; $conn->push('hi'); $conn->close; }
headers
Additional response headers. This is useful when you want to add Access Control headers:
headers => [ 'Access-Control-Allow-Origin' : 'http://localhost:5000', 'Access-Control-Allow-Credentials' : 'true' ]
It is recommended to use EventSource with polyfills to enable them in browsers that don't support SSE. This does not need any server changes, which is very handy. Take a look at EventSource.js and jquery.eventsource.
Set CORS headers:
headers => [ 'Access-Control-Allow-Origin' : 'http://original-domain', 'Access-Control-Allow-Credentials' : 'true' ]
If you try to set Origin to * some browsers will complain. So make sure to set the correct original domain.
Origin
*
When connecting to EventSource on the client side pass withCredentials option:
withCredentials
var es = new EventSource("http://another-domain", { withCredentials: true });
location /events { proxy_pass http://backend; proxy_buffering off; proxy_cache off; proxy_set_header Host $host; proxy_set_header Connection ''; proxy_http_version 1.1; chunked_transfer_encoding off; }
Jakob Voss (nichtich)
Viacheslav Tykhanovskyi, <viacheslav.t@gmail.com>
Copyright (C) 2015-, Viacheslav Tykhanovskyi
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
To install Plack::App::EventSource, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Plack::App::EventSource
CPAN shell
perl -MCPAN -e shell install Plack::App::EventSource
For more information on module installation, please visit the detailed CPAN module installation guide.