0
我正在寫Rails應用程序,並且我希望用戶在新消息保存到數據庫後能夠收到通知。對於websocket,我使用em-websocket寶石。連接後,我將客戶端ID和套接字實例存儲在數組中。Rails push EM-Socket
問題:如何從控制器\模型動作(例如before_save)將數據推送到客戶端?它能夠使用em-websocket嗎?
chat.rb
EVENTCHAT_CONFIG = YAML.load_file("#{Rails.root}/config/eventchat.yml")[Rails.env].symbolize_keys
#escape html/xss
include ERB::Util
Thread.abort_on_exception = true
Thread.new {
EventMachine.run {
@sockets = Array.new
EventMachine::WebSocket.start(EVENTCHAT_CONFIG) do |ws|
ws.onopen do
end
ws.onclose do
index = @sockets.index {|i| i[:socket] == ws}
client = @sockets.delete_at index
@sockets.each {|s| s[:socket].send h("#{client[:id]} has disconnected!")}
end
ws.onmessage do |msg|
client = JSON.parse(msg).symbolize_keys
case client[:action]
when 'connect'
@sockets.push({:id=>client[:id], :socket=>ws})
@sockets.each {|s| s[:socket].send h("#{client[:id]} has connected!")}
when 'say'
@sockets.each {|s| s[:socket].send h("#{client[:id]} says : #{client[:data]}")}
end
end
end
}
}