Skip to content

Instantly share code, notes, and snippets.

@josefrichter
Created May 14, 2011 13:28
Show Gist options
  • Save josefrichter/972209 to your computer and use it in GitHub Desktop.
Save josefrichter/972209 to your computer and use it in GitHub Desktop.
require 'redis'
require 'em-websocket'
require 'sinatra/base'
require 'sinatra'
SOCKETS = []
#@redis = Redis.new(:host => '127.0.0.1', :post => 6379)
@redis = Redis.new
# 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|
#@sockets.each {|s| s.send message}
@redis.publish('ws', message)
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|
# 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