2016-04-11 148 views
1

我試圖從我的控制器向所有註冊客戶端發送消息。 我發現要做到這一點的更好方法是在我的控制器中創建一個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時,所有的網絡套接字都會關閉。誰能幫我 ?

+0

做一個模塊,並使用這種方式。 。 http://stackoverflow.com/questions/33567167/how-can-i-push-to-faye-server-from-rails-controller/33567635#33567635 –

回答

0

使用的WebSocket客戶端

客戶端同時支持純文本WS協議和加密的WSS協議,並具有完全一樣的界面,你會在Web瀏覽器使用的插座。在電線上,它將自己標識爲hybi-13。

require 'faye/websocket' 
require 'eventmachine' 

EM.run { 
    ws = Faye::WebSocket::Client.new('ws://www.example.com/') 

    ws.on :open do |event| 
    p [:open] 
    ws.send('Hello, world!') 
end 

ws.on :message do |event| 
    p [:message, event.data] 
end 

ws.on :close do |event| 
    p [:close, event.code, event.reason] 
    ws = nil 
end 
} 

WebSocket客戶端還允許您通過狀態和標頭方法檢查握手響應的狀態和標頭。

要通過代理服務器連接,代理選項設置爲代理服務器的HTTP來源的,包括您所需要的任何授權信息和自定義頁眉:

ws = Faye::WebSocket::Client.new('ws://www.example.com/', [], {:proxy => { 
     :origin => 'http://username:[email protected]', 
     :headers => {'User-Agent' => 'ruby'} 
     } 
    }) 

以獲得更多幫助使用本link

+0

謝謝你從github上覆制完整的文檔,但它不'回答我的問題。 – Shrolox

0

我發現一個解決方案:

EM.run { 
      ws = Faye::WebSocket::Client.new(Rails.application.config.websocket_url) 
      ws.on :open do |event| 
      ws.send(JSON.dump(this_order.service_json)) 
      ws.close 
      end 
     } 

這等待套接字打開,然後發送消息並關閉。我不需要停止EventMachine。

相關問題