Upload
piotr-karbownik
View
5.007
Download
0
Embed Size (px)
DESCRIPTION
www.thesoftwarehouse.pl
Citation preview
Rails 4 & Server-Sent Events
Piotr Karbownik
SSE - EventSource API
Server-Sent Events (SSE) is a HTML5 standard describing how servers can initiate data transmission towards clients once an initial client connection has been established.
Browsers: Firefox, Chrome, Opera, Safari
SSE != Websockets
• SSE connections can only push data to the browser.
• It’s still HTTP - no new protocol
• Automatic reconnection
SSE - applications
• Notifications
• Continuous data streams
• News feeds
SSE – on the frontend
function newStream(){
var source = new EventSource('/streaming');
source.addEventListener('update', function(e) {
//do stuff
});
}
SSE – on the frontend
function newStream(){
var source = new EventSource('/streaming');
source.onmessage (function(e) {
//do stuff
});
}
EventSource Object Methods
onopen -When a connection to the server is opened
onmessage - When a message is received
onerror - When an error occurs
SSE – message format
Sample: event: my_event data: {"username": „Peter"}
event - The event's type. If this is specified, an event will be dispatched on the browser to the listener for the specified event name.
data - field for the message. id - the event ID to set the EventSource object's last event ID value retry - The reconnection time to use when attempting to send the
event.
Rails 4 - ActionController::Live
Live Streaming: the ability to send partial responses to the client immediately.
What about the server?
Server must support:
• Long running requests
• Live streaming
• Concurrency
• Examples: Puma, Rainbows, Thin
Config
environments /development.rb:
• config.cache_classes = true
• config.eager_load = true
database.yml
• pool == server max threads
• for Puma default is 16
Sample code - 1
Sample code
Sample code - 2
Summary
• Easy to implement
• Real time
• Good for notifications
• Problems with client connections amount and status.
…and the end
Sample apps:
https://github.com/cynamonium/srug-streamapp-2/
https://github.com/cynamonium/srug-streamapp-1