我正在编写 rails 应用程序,我希望用户在新消息保存到数据库后立即收到通知。对于 websocket,我使用的是 em-websocket gem。连接后,我将客户端 ID 和套接字实例存储在数组中。
问题:如何将数据从控制器\模型操作(例如 before_save)推送到客户端?是否可以使用 em-websocket 做到这一点?
聊天.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
}
}