-
-
Save danvine/5560410 to your computer and use it in GitHub Desktop.
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
# 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" |
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 '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 |
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
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment