Skip to content

Instantly share code, notes, and snippets.

@hpneo
Created February 8, 2013 08:07
Show Gist options
  • Save hpneo/4737381 to your computer and use it in GitHub Desktop.
Save hpneo/4737381 to your computer and use it in GitHub Desktop.
EventMachine based WebSocket server with em-websocket (https://github.com/igrigorik/em-websocket)
require 'em-websocket'
require 'json'
def parse_path(path)
data = path.split("/")
data.delete("")
{
:channel => data[0],
:event => data[1]
}
end
EventMachine.run do
@channels = {}
EventMachine::WebSocket.start(:host => "192.168.1.104", :port => 1234) do |ws|
puts "WebSocket server starting"
ws.onopen do |handshake|
puts "Welcome to Palladium"
socket_data = parse_path handshake.path
@channels[socket_data[:channel]] = EM::Channel.new
sid = @channels[socket_data[:channel]].subscribe { |msg| ws.send msg }
ws.onmessage do |msg|
message = JSON.parse(msg) rescue {}
puts "Receiving a message from #{socket_data[:channel]}:#{socket_data[:event]}"
response = {
:channel => socket_data[:channel],
:event => socket_data[:event],
:data => msg
}
@channels[socket_data[:channel]].push(response.to_json)
end
ws.onclose do
puts "Au revoir!"
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment