Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
web sockets with eventmachine and redis pub/sub
# A sample Gemfile
source ""
gem "redis"
gem 'eventmachine', :git => 'git://'
gem "em-hiredis"
# gem "em-synchrony"
gem "em-websocket"
require 'rubygems'
require 'bundler/setup'
require 'em-websocket'
require 'em-hiredis' do
@channel =
@redis = EM::Hiredis.connect
puts 'subscribing to redis'
@redis.on(:message){|channel, message|
puts "redis -> #{channel}: #{message}"
@channel.push message
# Creates a websocket listener
EventMachine::WebSocket.start(:host => '', :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
ws.onmessage { |msg|
@channel.push "<#{sid}>: #{msg}"
ws.onclose {
<!DOCTYPE html>
<script type="text/javascript">
function onMessage(evt) {
con = document.getElementById("console");
con.innerHTML +=;
con.innerHTML += '<br />';
websocket = new WebSocket("ws://localhost:8081");
websocket.onmessage = function(evt) { onMessage(evt); };
<div id="console">

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

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

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