Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Server-Sent Events with Ruby Sinatra

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!

like image 462
user248257 Avatar asked Mar 08 '11 01:03

user248257


People also ask

What are the server-sent events in HTML5?

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.

Is server-sent events part of HTML5?

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.


1 Answers

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

like image 139
Konstantin Haase Avatar answered Sep 30 '22 19:09

Konstantin Haase