Created
June 4, 2012 17:46
-
-
Save jboesch/2869793 to your computer and use it in GitHub Desktop.
WebSocket server in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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