문제

I have written a program for reading data from an html file to ruby program using websocket. I am including the code below:

EventMachine::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
      ws.onopen { |handshake|
      puts "WebSocket connection open #{ws}"

     # Access properties on the EM::WebSocket::Handshake object, e.g.
     # path, query_string, origin, headers

     # Publish message to the client
     # ws.send "Hello Client, you connected to #{handshake.path}"
    }


    ws.onclose { puts "Connection closed" }

    ws.onmessage { |msg|
         puts "Recieved message: #{msg}"

         ws.send "#{msg}"
    }

end

This is working properly.It recieves whatever data send from my html page. Now, what I need is to keep track of the connections to this server and send the recieved message to all the available connections. The 'send' function here used can send only to a specified connection.

도움이 되었습니까?

해결책

You asking for a basic chat server?

Just store the connections in a list (or hash). People tend to include in a hash to make it easier to remove them If this is in a class, use @connections instead of $connections

GL

$connections = {}
EventMachine::WebSocket.run(:host => "0.0.0.0", :port => 8080) do |ws|
  ws.onopen
    $connections[ws] = true
  end
  ws.onclose do
    $connections.delete(ws)
  end
  ws.onmessage do |msg|
    $connections.each { |c, b| c.send msg }
  end
end

다른 팁

You could use EventMachine in combination with Faye and Faye/Websocket

You will need faye/websocket for your browser-based clients or just faye for your ruby clients.

The idea is that with Faye you create a channel and then you subscribe your clients to that channel. Then you push from your server the data you want to this channel and the clients subscribed will receive this data.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top