Skip to content

Instantly share code, notes, and snippets.

@jessedearing
Created November 30, 2010 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessedearing/721529 to your computer and use it in GitHub Desktop.
Save jessedearing/721529 to your computer and use it in GitHub Desktop.
<!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>
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