Skip to content

Instantly share code, notes, and snippets.

@jboesch
Created June 4, 2012 17:46
Show Gist options
  • Save jboesch/2869793 to your computer and use it in GitHub Desktop.
Save jboesch/2869793 to your computer and use it in GitHub Desktop.
WebSocket server in Ruby
# You need to first download em-websocket at https://github.com/igrigorik/em-websocket
# Then install the gem then name this file to "server.rb" and run it: "ruby server.rb"
# This is a combination of code from the example at http://www.igvita.com/2009/12/22/ruby-websockets-tcp-for-the-browser/
# and at http://jessedearing.com/nodes/4-pubsubbin-with-redis-eventmachine-and-websockets to publish to all connected sockets.
require 'em-websocket'
SOCKETS = []
EventMachine::WebSocket.start(:host => "127.0.0.1", :port => 8080) do |ws|
ws.onopen do
# When someone connects I want to add that socket to the SOCKETS array that
# I instantiated above
SOCKETS << ws
end
ws.onclose do
# Upon the close of the connection I remove it from my list of running sockets
SOCKETS.delete ws
end
ws.onmessage {
|msg| ws.send "#{msg}"
SOCKETS.each {|s| s.send msg}
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment