I'm trying to broadcast from my controller a message to all registered clients. The better way I found to do this is to create a Faye client in my controller, send my message, and close it right after message is sent.
#my_controller.rb
EM.run {
ws = Faye::WebSocket::Client.new(Rails.application.config.websocket_url)
ws.send(JSON.dump(this_order.service_json))
EM.stop
}
Although this code partially works, it closes all my browser connections to Faye.
Faye is implemented in a middleware, like this:
class FayeMiddleware
KEEPALIVE_TIME = 30 # in seconds
def initialize(app)
@app = app
@clients = []
end
def call(env)
if Faye::WebSocket.websocket?(env)
# WebSockets logic goes here
ws = Faye::WebSocket.new(env, nil, {ping: KEEPALIVE_TIME })
ws.on :open do |event|
p [:open, ws.object_id]
@clients << ws
end
ws.on :close do |event|
p [:close, ws.object_id, event.code, event.reason]
@clients.delete(ws)
ws = nil
end
ws.on :message do |event|
p [:message, event.data]
puts event.data
@clients.each {|client| client.send(event.data) }
end
# Return async Rack response
ws.rack_response
else
@app.call(env)
end
end
end
I made this code referring to this tutorial.
I don't understand why all my web sockets get closed when I stop my EM. Can anyone help me ?