I'm new to Ruby and Sinatra, I'm trying to setup a simple HTML5 Server-Sent Event with it, The code below works fine in Chrome developer builds but fails in Non Developer Builds and Safari on both Windows7 and OSX.
The error message in the browser console is "Failed to load resource: cancelled"
var source = new EventSource('pull');
source.addEventListener('message', function(e) {
console.log(e.data);
}, false);
source.addEventListener('open', function(e) {
// Conn open
}, false);
source.addEventListener('error', function(e) {
if (e.eventPhase == EventSource.CLOSED) {
// Connection was closed.
}
}, false);
With the below Sinatra route
get '/pull' do
content_type 'text/event-stream'
newevent = false
response = "data: "+newevent.inspect+" \n\n"
end
I have tried similar server side code with JSP and Tomcat and it works fine on all browser.
What do I need to know about Sinatra? thanks!
A server-sent event is when a web page automatically gets updates from a server. This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continuously from your web server to the visitor's browser.
If you want to support events, you have to create your own body object. Take a look at at the implementation and usage. Make sure you run it with Thin or Rainbows. It will not work on Mongrel or WEBrick.
You can watch the presentation at Confreaks (its source code at GitHub).
Update: Here is one more example (Simple Chat Application using the Sinatra Streaming API).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With