Reputation: 4852
I'm trying to build a rails websocket application using em-websocket. I have placed the below code in a file config/initalizers/websocket.rb but when I run 'rails server' the application does not start. if I remove the code it starts fine. The same thing occurs on my local machine and server.
require 'eventmachine'
require 'em-websocket'
EventMachine.run {
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080) do |ws|
ws.onopen {
puts "WebSocket connection open"
ws.send "Hello Client"
}
ws.onclose { puts "Connection closed" }
ws.onmessage { |msg|
puts "Recieved message: #{msg}"
ws.send "Pong: #{msg}"
}
end
puts "Websocket started"
}
I get this console print out
=> Booting WEBrick
=> Rails 3.2.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Websocket started
If i remove the above code it starts fine and i get:
=> Booting WEBrick
=> Rails 3.2.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-12-21 04:19:52] INFO WEBrick 1.3.1
[2012-12-21 04:19:52] INFO ruby 1.9.3 (2012-04-20) [i386-mingw32]
[2012-12-21 04:19:52] INFO WEBrick::HTTPServer#start: pid=1484 port=3000
Any ideas would be highly appreciated
Upvotes: 0
Views: 877
Reputation: 674
First solution:
Second solution:
Put your code inside a Thread in order to avoid main thread blocking.
require 'eventmachine'
require 'em-websocket'
Thread.new {
# Your websocket code
}
Upvotes: 0
Reputation: 1836
I haven't used this gem before, but it looks like you are starting a server in the initializer.
Execution is then paused on the main thread until your Websockets server returns control to it (which will presumably be when your websockets server is closed).
You probably want the server as a separate app, so you have a server that responds to HTTP (your Rails server), and a server that responds to the sockets (what your initializer file is the start of).
Upvotes: 3