Search code examples
rubysinatrawebsocketeventmachinepadrino

padrino && websockets


i'm looking for a way to open and use websockets from within a Padrino application. i know Padrino works with a single thread but i'm looking for a way to open websockets and share variables between its "onopen" "onclose" "onmessage" methods and Padrino controllers.

any idea how it's done ?

links i looked into:

Examples of Eventmachine usage with Padrino and Sinatra (only Sinatra worked for me) em-websocket on GitHub

UPDATE 1: this is my main.rb:

    require 'rubygems'      # <-- Added this require
require 'em-websocket'
require 'padrino-core'
require 'thin'

require File.expand_path("../config/boot.rb", __FILE__)

SOCKETS = []
EventMachine.run do     # <-- Changed EM to EventMachine
#  class App < Sinatra::Base
#      get '/' do
#          SOCKETS.each {|s| s.send "fooooo"}
#          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!!!!"
          SOCKETS << ws
      }

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

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

  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!
  Thin::Server.start Padrino.application, '0.0.0.0', 3000

end

i'm getting this exception:

/home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `require': no such file to load -- daemons (LoadError)
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/daemonizing.rb:2:in `<top (required)>'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:50:in `<class:Server>'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:48:in `<module:Thin>'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/thin-1.2.11/lib/thin/server.rb:1:in `<top (required)>'
    from main.rb:39:in `block in <main>'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `call'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
    from /home/cstore/.rvm/gems/ruby-1.9.2-p290@runtime/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
    from main.rb:9:in `<main>'

UPDATE 2: Resolved thanks to Nathan ! I just added 'daemons' to Gemfile and reloaded my application.


Solution

  • Maybe you need to install daemons:

    Edit your Gemfile:

    # Adding this
    gem 'daemons'
    

    Install missing gems:

    $ bundle install