Skip to content

Instantly share code, notes, and snippets.

@josefrichter
Created May 14, 2011 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josefrichter/972342 to your computer and use it in GitHub Desktop.
Save josefrichter/972342 to your computer and use it in GitHub Desktop.
require 'redis'
require 'em-websocket'
require 'sinatra/base'
#require 'sinatra'
require 'ruby-debug'
SOCKETS = []
REDIS = Redis.new(:host => '0.0.0.0', :port => 6379)
# Creating a thread for the EM event loop
Thread.new do
EventMachine.run do
class App < Sinatra::Base
# Sinatra code here
get '/' do
erb :index
end
end
# Creates a websocket listener
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
ws.onopen do
# When someone connects I want to add that socket to the SOCKETS array that
# I instantiated above
puts 'creating socket'
SOCKETS << ws
end
ws.onmessage do |message|
message.delete!('"')
#SOCKETS.each {|s| s.send message}
#debugger
#puts "from browser: "+message
pub = REDIS.publish('ws', message.to_s)
puts pub
end
ws.onclose do
# Upon the close of the connection I remove it from my list of running sockets
puts 'closing socket'
SOCKETS.delete ws
end
end #EventMachine::WebSocket
App.run!({:port => 3000})
end #EventMachine.run
end #Thread
# Creating a thread for the redis subscribe block
Thread.new do
REDIS.subscribe('ws') do |on|
#debugger
# When a message is published to 'ws'
on.message do |chan, msg|
puts "sending message: #{msg}"
# Send out the message on each open socket
SOCKETS.each {|s| s.send msg}
end
end
end
sleep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment