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