2015-05-28 75 views
0

我有兩個websocket客戶端,我想在它們之間交換信息。em-websocket send()通過2臺服務器從一個客戶端發送到另一個客戶端

比方說,我有兩個套接字服務器實例,1st檢索私人信息,過濾它併發送到第二個。

require 'em-websocket' 

EM.run do 
    EM::WebSocket.run(host: '0.0.0.0', port: 19108) do |manager_emulator| 
    # retrieve information. After that I need to send it to another port (9108) 
    end 

    EM::WebSocket.run(host: '0.0.0.0', port: 9108) do |fake_manager| 
    # I need to send filtered information here 
    end 
end 

我試過去做一些事情,但是我得到了一般的黑暗代碼,我不知道如何實現這個功能。

+0

你爲什麼要在定義服務的過程中引發異常? ('raise manager_emulator.inspect') – Myst

+0

omg,我用它來調試。我現在將它刪除 – asiniy

回答

0

我發現了一種方法,通過em-websocket寶石!你只需要在eventmachine塊之外定義變量。類似的東西

require 'em-websocket' 

message_sender = nil 

EM.run do 
    # message sender 
    EM::WebSocket.run(host: '0.0.0.0', port: 19108) do |ws| 
    ws.onopen { message_sender = ws } 
    ws.onclose { message_sender = nil } 
    end 

    # message receiver 
    EM::WebSocket.run(host: '0.0.0.0', port: 9108) do |ws| 
    ws.onmessage { |msg| message_sender.send(msg) if message_sender } 
    end 
end 
+0

很好的解決方法。但是在我看來,如果Event Machine是多線程的(它可能不應該)或者通過異步事件(我認爲它可以)循環,那麼當您有多個客戶端時,您將面臨數據損壞和衝突的風險。 ...但我可能是錯的。 EM旨在規避其中一些問題。 – Myst

0

我不知道你會怎麼做,使用EM。

我假設你需要讓fake_manager監聽由manager_emulator觸發的事件。

如果您使用websocket web應用程序框架,這將是相當容易的。例如,在Plezi web-app framework你可以寫這樣的東西:

# try the example from your terminal. 
# use http://www.websocket.org/echo.html in two different browsers to observe: 
# 
# Window 1: http://localhost:3000/manager 
# Window 2: http://localhost:3000/fake 

require 'plezi' 

class Manager_Controller 
    def on_message data 
     FakeManager_Controller.broadcast :_send, "Hi, fake! Please do something with: #{data}\r\n- from Manager." 
     true 
    end 
    def _send message 
     response << message 
    end 
end 
class FakeManager_Controller 
    def on_message data 
     Manager_Controller.broadcast :_send, "Hi, manager! This is yours: #{data}\r\n- from Fake." 
     true 
    end 
    def _send message 
     response << message 
    end 
end 
class HomeController 
    def index 
     "use http://www.websocket.org/echo.html in two different browsers to observe this demo in action:\r\n" + 
     "Window 1: http://localhost:3000/manager\r\nWindow 2: http://localhost:3000/fake\r\n" 
    end 
end 

# # optional Redis URL: automatic broadcasting across processes or machines: 
# ENV['PL_REDIS_URL'] = "redis://username:[email protected]:6379" 

# starts listening with default settings, on port 3000 
listen 

# Setup routes: 
# They are automatically converted to the RESTful route: '/path/(:id)' 
route '/manager', Manager_Controller 
route '/fake', FakeManager_Controller 
route '/', HomeController 

# exit terminal to start server 
exit 

祝你好運!

P.S.

如果您打算繼續使用EM,則可以考慮使用Redis來推送和訂閱兩個端口之間的事件。

+0

感謝您的幫助!我已經找到了一種方法,我可以使用eventmachine來實現它。請檢查答案 – asiniy

相關問題