Skip to content

Instantly share code, notes, and snippets.

@airy
Created December 2, 2015 21:58
Show Gist options
  • Save airy/35584244ce4af291e739 to your computer and use it in GitHub Desktop.
Save airy/35584244ce4af291e739 to your computer and use it in GitHub Desktop.
simple ws echo server
require 'sinatra'
require 'sinatra-websocket'
require 'tilt/erubis'
set :server, 'thin'
set :sockets, []
get '/' do
if !request.websocket?
erb :index
else
request.websocket do |ws|
ws.onopen do
ws.send("Hello World!")
settings.sockets << ws
end
ws.onmessage do |msg|
EM.next_tick { settings.sockets.each{ |s| s.send(msg) } }
end
ws.onclose do
warn("websocket closed")
settings.sockets.delete(ws)
end
end
end
end
__END__
@@ index
<html>
<body>
<h1>Simple Echo Server</h1>
<form id="form">
<input type="text" id="input" placeholder="say something"></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 = "";
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