Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

web sockets with eventmachine and redis pub/sub

View Gemfile
1 2 3 4 5 6 7 8
# A sample Gemfile
source "http://rubygems.org"
 
gem "redis"
gem 'eventmachine', :git => 'git://github.com/eventmachine/eventmachine.git'
gem "em-hiredis"
# gem "em-synchrony"
gem "em-websocket"
View Gemfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
require 'rubygems'
require 'bundler/setup'
require 'em-websocket'
require 'em-hiredis'
 
EM.run do
@channel = EM::Channel.new
 
@redis = EM::Hiredis.connect
puts 'subscribing to redis'
@redis.subscribe('ws')
@redis.on(:message){|channel, message|
puts "redis -> #{channel}: #{message}"
@channel.push message
}
 
# Creates a websocket listener
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8081) do |ws|
puts 'Establishing websocket'
ws.onopen do
puts 'client connected'
puts 'subscribing to channel'
sid = @channel.subscribe do |msg|
puts "sending: #{msg}"
ws.send msg
end
 
ws.onmessage { |msg|
@channel.push "<#{sid}>: #{msg}"
}
 
ws.onclose {
@channel.unsubscribe(sid)
}
end
end
end
View Gemfile
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<!DOCTYPE html>
 
<html>
<head>
<title>Websockets!</title>
<script type="text/javascript">
function onMessage(evt) {
con = document.getElementById("console");
con.innerHTML += evt.data;
con.innerHTML += '<br />';
}
websocket = new WebSocket("ws://localhost:8081");
websocket.onmessage = function(evt) { onMessage(evt); };
</script>
</head>
 
<body>
<div id="console">
</div>
</body>
</html>

thanks @gvarela. It works. You save my day!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.