Created
April 15, 2013 04:00
Notification's Spike => EventMachine + WebSocket + Redis (PubSub)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'em-websocket' | |
require 'sinatra/base' | |
require 'thin' | |
require 'redis' | |
require 'json' | |
require 'pry' | |
# SOCKETS = [] | |
# Thread.new do | |
# redis = Redis.new | |
# redis.subscribe('cliente_1') do |on| | |
# on.message do |channel, message| | |
# SOCKETS.each do |s| | |
# s.send message | |
# end | |
# end | |
# end | |
# end | |
EventMachine.run do | |
class App < Sinatra::Base | |
set :bind, '4567' | |
get '/' do | |
erb :index | |
end | |
end | |
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws| | |
# ws.onopen { | |
# SOCKETS << ws | |
# } | |
ws.onmessage { |message| | |
obj = JSON.parse message | |
case obj['action'] | |
when 'subscribe' | |
Thread.new do | |
redis = Redis.new | |
redis.subscribe(obj['channel']) do |on| | |
on.message do |channel, message| | |
ws.send message | |
end | |
end | |
end | |
when 'publish' | |
redis = Redis.new | |
redis.publish obj['channel'], obj['message'] | |
end | |
} | |
# ws.onclose { | |
# SOCKETS.delete ws | |
# } | |
end | |
App.run! | |
end | |
__END__ | |
@@ index.rhtml | |
<html> | |
<head> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> | |
<script> | |
jQuery(document).ready(function($) { | |
var ws = new WebSocket("ws://192.168.0.101:8080"); | |
ws.onmessage = function(evt) { | |
$("#show").html(evt.data); | |
} | |
$("#connect").click(function() { | |
ws.send(JSON.stringify({ | |
'channel': $("#client_id").val(), | |
'action': 'subscribe', | |
'message': '', | |
})); | |
}); | |
$("#send").click(function() { | |
ws.send(JSON.stringify({ | |
'channel': $("#server_id").val(), | |
'action': 'publish', | |
'message': $("#message").val(), | |
})); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<p id="show">Ola, mundo!</p> | |
FROM: <input type='text' id="client_id"> <br> | |
TO: <input type='text' id="server_id"> <br> | |
MESSAGE: <input type='text' id="message"> <br> | |
<input type="button" id="connect" value="connect"> | |
<input type="button" id="send" value="send"> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment