Skip to content

@gvarela /Gemfile
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
web sockets with eventmachine and redis pub/sub
# 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"
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
<!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>
@AmitPatel-BoTreeConsulting

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

@HParker

Thanks for the example! almost 4 years later exactly and this still works with only one change
line 9 is now: @redis = EM::Hiredis.connect.pubsub

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.