37

I have been using Sinatra for sometime now and I would like to add some realtime features to my web-app by pushing the data via websockets.

I have successfully used the gem 'em-websocket' on its own, but have not been able to write one ruby file that has a sinatra web server AND a web-socket server.

I've tried spinning the run! or start! methods off in separate threads with no success.

Has anyone gotten this to work?

I want to have them in the same file as I can then share variables between the two servers.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
Poul
  • 3,426
  • 5
  • 37
  • 43

5 Answers5

27

Did not try it, but should not be too hard:

require 'em-websocket'
require 'sinatra/base'
require 'thin'

EM.run do
  class App < Sinatra::Base
    # Sinatra code here
  end

  EM::WebSocket.start(:host => '0.0.0.0', :port => 3001) do
    # Websocket code here
  end

  # You could also use Rainbows! instead of Thin.
  # Any EM based Rack handler should do.
  Thin::Server.start App, '0.0.0.0', 3000
end

Also, Cramp has a websocket implementation that works directly with Thin/Rainbows! you might be able to extract, so you won't even need to run the server on another port.

Kamiel Wanrooij
  • 12,164
  • 6
  • 37
  • 43
Konstantin Haase
  • 25,687
  • 2
  • 57
  • 59
  • That's is pretty much how I've done it. I have a related question however which is how do I decode the `Rack::Server::Cookie` (set in the `Sinatra` class) value returned in the `handshake` passed by the client to `ws.onopen`. See my question in more detail at http://stackoverflow.com/questions/16312024/how-to-decode-a-cookie-from-the-header-of-a-websocket-connection-handshake-rub – Dave Sag May 03 '13 at 02:02
20

Thanks Konstantin... that worked! I had to tweak your code slightly. I added comments where I changed it.

-poul

require 'rubygems'      # <-- Added this require
require 'em-websocket'
require 'sinatra/base'
require 'thin'

EventMachine.run do     # <-- Changed EM to EventMachine
  class App < Sinatra::Base
      get '/' do
          return "foo"
      end
  end

  EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws| # <-- Added |ws|
      # Websocket code here
      ws.onopen {
          ws.send "connected!!!!"
      }

      ws.onmessage { |msg|
          puts "got message #{msg}"
      }

      ws.onclose   {
          ws.send "WebSocket closed"
      }

  end

  # You could also use Rainbows! instead of Thin.
  # Any EM based Rack handler should do.
  App.run!({:port => 3000})    # <-- Changed this line from Thin.start to App.run!
end
Poul
  • 3,426
  • 5
  • 37
  • 43
  • This works well. One question though, how can the EventMachine socket events access the session info to authenticate that events are comming from a properly authenticated user? – Dave Sag Apr 21 '13 at 08:15
  • I've outlined this as per my comment on @Konstanti Haase's answer, as a new question - see http://stackoverflow.com/questions/16312024/how-to-decode-a-cookie-from-the-header-of-a-websocket-connection-handshake-rub – Dave Sag May 03 '13 at 02:03
17

I stumbled onto this websocket-rack github project which is basically a rackified em-websocket and actually got it to work nicely side-by-side with a Sinatra app. Here's my config.ru:

require 'rubygems'
require 'rack/websocket'
require 'sinatra/base'

class WebSocketApp < Rack::WebSocket::Application
  # ...
end

class SinatraApp < Sinatra::Base
  # ...
end

map '/ws' do
  run WebSocketApp.new
end

map '/' do
  run SinatraApp
end

Have fun!
Colin

12

I've been using sinatra-websocket. It let's you run the websocket server in the same process and on the same port as Sinatra.

Disclaimer: I'm the maintainer.

require 'sinatra'
require 'sinatra-websocket'

set :server, 'thin'
set :sockets, []

get '/' do
  if !request.websocket?
    erb :index
  else
    request.websocket do |ws|
      ws.onopen do
        ws.send("Hello World!")
        settings.sockets << ws
      end
      ws.onmessage do |msg|
        EM.next_tick { settings.sockets.each{|s| s.send(msg) } }
      end
      ws.onclose do
        warn("websocket closed")
        settings.sockets.delete(ws)
      end
    end
  end
end

__END__
@@ index
<html>
  <body>
     <h1>Simple Echo & Chat Server</h1>
     <form id="form">
       <input type="text" id="input" value="send a message"></input>
     </form>
     <div id="msgs"></div>
  </body>

  <script type="text/javascript">
    window.onload = function(){
      (function(){
        var show = function(el){
          return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; }
        }(document.getElementById('msgs'));

        var ws       = new WebSocket('ws://' + window.location.host + window.location.pathname);
        ws.onopen    = function()  { show('websocket opened'); };
        ws.onclose   = function()  { show('websocket closed'); }
        ws.onmessage = function(m) { show('websocket message: ' +  m.data); };

        var sender = function(f){
          var input     = document.getElementById('input');
          input.onclick = function(){ input.value = "" };
          f.onsubmit    = function(){
            ws.send(input.value);
            input.value = "send a message";
            return false;
          }
        }(document.getElementById('form'));
      })();
    }
  </script>
</html>
simulacre
  • 1,223
  • 8
  • 7
  • ..being this the quickest way to use websocket with sinatra (to my eyes), can I ask which disadvantages this approach brings compared to using 'em-websocket', subclassing Sinatra::Base, and "manually" plugging into the event loop ? – Redoman Dec 14 '12 at 19:38
  • also could anyone give a short explaination on why is "next_tick" needed here? – Redoman Dec 16 '12 at 04:54
  • @@simulacre -- Any ideas how to make this work on a load balanced setup? I mean from the example above, every Sinatra process would then have its own "settings.sockets" array turning the process stateful? – Sunder Dec 30 '12 at 03:26
  • Absolutely lovely :) – Guillaume Roderick May 12 '16 at 15:41
8

FYI, you can also use Padrino apps with EventMachine (as they are subsets of Sinatra apps):

require 'rubygems'
require 'eventmachine'
require 'padrino-core'
require 'thin'
require ::File.dirname(__FILE__) + '/config/boot.rb'

EM.run do
  Thin::Server.start Padrino.application, '0.0.0.0', 3000
end
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
user546469
  • 81
  • 1
  • 2