Skip to content

Instantly share code, notes, and snippets.

@gvarela
Created May 5, 2011 16:30
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 12 You must be signed in to fork a gist
  • Save gvarela/957367 to your computer and use it in GitHub Desktop.
Save gvarela/957367 to your computer and use it in GitHub Desktop.
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>
@amitpatelx
Copy link

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

@HParker
Copy link

HParker commented May 5, 2015

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

@tsball
Copy link

tsball commented Nov 13, 2020

@redis = EM::Hiredis.connect.pubsub + 1
Otherwise EventMachine::WebSocket.start can not use redis, it will block by @redis.subscribe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment