horseyguy
horseyguy

Reputation: 29915

How to use eventmachine, rails, and websockets?

i have the following sinatra code, how do i do the equivalent but for a rails app? specifically, want to start rails with thin inside the reactor loop, while also using a websocket server in there too.

require 'bundler'
Bundler.require

class App < Sinatra::Base
  get '/' do
    slim :index
  end
end

EM.run do
  EM::WebSocket.start(:host => '0.0.0.0', :port => 3001) do |ws|
    # websocket stuff goes here
  end

  # start sinatra in a thin server instance here (but i want to start a rails app instead)
  Thin::Server.start App, '0.0.0.0', 3000
end

Upvotes: 0

Views: 468

Answers (1)

tbuehlmann
tbuehlmann

Reputation: 9110

I'd setup an initializer like config/initializers/websocket.rb with this:

EM.next_tick do
  EM::WebSocket.start(:host => '0.0.0.0', :port => 3001) do |ws|
    # websocket stuff goes here
  end
end

Also, add gem 'thin' to the Gemfile and start the server simply with $ rails s. When the EM reactor starts, the queued next_tick block will be called and the websocket server starts running.

You could also put the websocket code in some file in lib/ and start it through an initializer, might be cleaner.

Upvotes: 1

Related Questions