Last active
April 25, 2016 14:27
-
-
Save ohcibi/5418898 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
require 'rubygems' | |
require 'bundler/setup' | |
require 'sinatra' | |
require 'sinatra-websocket' | |
require 'redis' | |
set :server, 'thin' | |
set :redis, Redis.new | |
set(:watcher, Thread.new do | |
redis = Redis.new | |
Thread.current['sockets'] = [] | |
redis.subscribe 'foobar' do |on| | |
on.message do |channel, message| | |
Thread.current['sockets'].each do |s| | |
s.send message | |
end | |
end | |
end | |
end) | |
get '/' do | |
if !request.websocket? | |
erb :index | |
else | |
request.websocket do |ws| | |
ws.onopen do | |
ws.send("Hello World!") | |
settings.watcher['sockets' << ws | |
end | |
ws.onmessage do |msg| | |
redis.publish 'foobar', msg | |
end | |
ws.onclose do | |
warn("wetbsocket closed") | |
settings.watcher['sockets'].delete(ws) | |
end | |
end | |
end | |
end | |
__END__ | |
@@ index | |
<html> | |
<body> | |
<h1>Simple Echo & Chat Server</h1> | |
<form id="form"> | |
<input type="text" id="input" value="send a message"></input> | |
</form> | |
<div id="msgs"></div> | |
</body> | |
<script type="text/javascript"> | |
window.onload = function(){ | |
(function(){ | |
var show = function(el){ | |
return function(msg){ el.innerHTML = msg + '<br />' + el.innerHTML; } | |
}(document.getElementById('msgs')); | |
var ws = new WebSocket('ws://' + window.location.host + window.location.pathname); | |
ws.onopen = function() { show('websocket opened'); }; | |
ws.onclose = function() { show('websocket closed'); } | |
ws.onmessage = function(m) { show('websocket message: ' + m.data); }; | |
var sender = function(f){ | |
var input = document.getElementById('input'); | |
input.onclick = function(){ input.value = "" }; | |
f.onsubmit = function(){ | |
ws.send(input.value); | |
input.value = "send a message"; | |
return false; | |
} | |
}(document.getElementById('form')); | |
})(); | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That saved my day! Thanks.