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!
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).