Any success with Sinatra working together with EventMachine WebSockets?
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', 3000end
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.
Thanks Konstantin... that worked! I had to tweak your code slightly. I added comments where I changed it.
-poul
require 'rubygems' # <-- Added this requirerequire '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
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 # ...endclass SinatraApp < Sinatra::Base # ...endmap '/ws' do run WebSocketApp.newendmap '/' do run SinatraAppend
Have fun!
Colin