我試圖從我的控制器向所有註冊客戶端發送消息。 我發現要做到這一點的更好方法是在我的控制器中創建一個Faye客戶端,發送我的消息,並在發送消息後立即關閉它。Rails Faye Websocket客戶端只發送一條消息
#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
}
儘管此代碼部分起作用,它會關閉我所有與Faye的瀏覽器連接。
王菲在中間件實現的,就像這樣:
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
我做了這個代碼參照this教程。
我不明白爲什麼當我停止EM時,所有的網絡套接字都會關閉。誰能幫我 ?
做一個模塊,並使用這種方式。 。 http://stackoverflow.com/questions/33567167/how-can-i-push-to-faye-server-from-rails-controller/33567635#33567635 –