Skip to content

Instantly share code, notes, and snippets.

@patrickdet
Forked from lifo/websock_action.rb
Created January 10, 2010 12:38
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 patrickdet/273476 to your computer and use it in GitHub Desktop.
Save patrickdet/273476 to your computer and use it in GitHub Desktop.
# Requires Cramp 0.8+
require 'rubygems'
require 'usher'
require 'cramp/controller'
Cramp::Controller::Websocket.backend = :thin
class WebsockAction < Cramp::Controller::Websocket
periodic_timer :send_hello_world, :every => 2
on_data :received_data
on_finish :socket_closed
def start
@id = params[:id] || 'unknown id'
end
def received_data(data)
if data =~ /fuck/
render "#{@id}: You cant say fuck in here"
finish
else
render "#{@id}: Got your #{data}"
end
end
def send_hello_world
render "#{@id}: Hello from the Server!"
end
def socket_closed
puts "Client gone away :("
end
end
Thin::Logging.debug = true
routes = Usher::Interface.for(:rack) do
add('/(:id)').to(WebsockAction)
end
Rack::Handler::Thin.run routes, :Port => 3000
<html>
<!-- Yanked from http://www.igvita.com/2009/12/22/ruby-websockets-tcp-for-the-browser -->
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
<script>
$(document).ready(function(){
function debug(str){ $("#debug").append("<p>"+str+"</p>"); };
ws = new WebSocket("ws://0.0.0.0:3000/1");
ws.onmessage = function(evt) { $("#msg").append("<p>"+evt.data+"</p>"); };
ws.onclose = function() { debug("socket closed"); };
ws.onopen = function() {
debug("connected...");
ws.send("hello server");
setTimeout('ws.send("5 secs")', 5000);
setTimeout('ws.send("10 secs")', 10000);
setTimeout('ws.send("15 secs")', 15000);
};
});
</script>
</head>
<body>
<div id="debug"></div>
<div id="msg"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment