ruby-on-railsrubywebsocketem-websocket

em-websocket send() send from one client to another through 2 servers


I have two websocket clients, and I want to exchange information between them.

Let's say I have two instances of socket servers, and 1st is retrieve private information, filter it and send to the second one.

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

I've tried to do something, but I got usual dark code and I don't know how to implement this functionality.


Solution

  • I've found a way how to do it through em-websocket gem! You need just define variables outside of eventmachine block. Something like that

    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