Created
November 30, 2010 11:15
-
-
Save jessedearing/721529 to your computer and use it in GitHub Desktop.
This file contains 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> | |
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> |
This file contains 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 'redis' | |
require 'em-websocket' | |
SOCKETS = [] | |
@redis = Redis.new(:host => '127.0.0.1', :post => 6379) | |
# Creating a thread for the EM event loop | |
Thread.new do | |
EventMachine.run do | |
# Creates a websocket listener | |
EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 8081) do |ws| | |
ws.onopen do | |
# When someone connects I want to add that socket to the SOCKETS array that | |
# I instantiated above | |
puts 'creating socket' | |
SOCKETS << ws | |
end | |
ws.onclose do | |
# Upon the close of the connection I remove it from my list of running sockets | |
puts 'closing socket' | |
SOCKETS.delete ws | |
end | |
end | |
end | |
end | |
# Creating a thread for the redis subscribe block | |
Thread.new do | |
@redis.subscribe('ws') do |on| | |
# When a message is published to 'ws' | |
on.message do |chan, msg| | |
puts "sending message: #{msg}" | |
# Send out the message on each open socket | |
SOCKETS.each {|s| s.send msg} | |
end | |
end | |
end | |
sleep |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment