Skip to content

Instantly share code, notes, and snippets.

@tobi
Created September 10, 2009 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tobi/184760 to your computer and use it in GitHub Desktop.
Save tobi/184760 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'cgi'
class Room < EM::Channel
end
$room = Room.new
$welcome_html = DATA.read
class Chatter < EventMachine::Connection
include EventMachine::HttpServer
def unbind
$room.unsubscribe(@subscription)
end
def parse_params
params = ENV['QUERY_STRING'].split('&').inject({}) {|p, s| k,v=s.split('=');p[k.to_s]=CGI.unescape(v.to_s);p}
params
end
def process_http_request
puts "#{object_id}: #{method = ENV["REQUEST_METHOD"]} #{action = ENV["PATH_INFO"]} #{ENV["QUERY_STRING"]}"
params = parse_params
case action
when '/'
response = EventMachine::DelegatedHttpResponse.new( self )
response.headers['Content-Type'] = 'text/html'
response.status = 200
response.content = $welcome_html
response.send_response
when '/poll'
response = EventMachine::DelegatedHttpResponse.new( self )
@subscription = $room.subscribe do |msg|
response.headers['Content-Type'] = 'text/plain'
response.status = 200
response.content = msg
response.send_response
end
when '/say'
$room.push params['msg']
response = EventMachine::DelegatedHttpResponse.new( self )
response.headers['Content-Type'] = 'text/plain'
response.status = 200
response.send_response
else
response = EventMachine::DelegatedHttpResponse.new( self )
response.headers['Content-Type'] = 'text/html'
response.status = 404
response.content = %|<h1>Not Found</h1>"|
response.send_response
end
end
end
EventMachine::run {
EventMachine.epoll
EventMachine::start_server("0.0.0.0", 8080, Chatter)
puts "Listening on 8080..."
}
__END__
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js">
</script>
<script>
function say(msg) {
$('chat').appendChild(new Element('p').update("<b>Someone</b> said: " + msg));
}
function poll(){
new Ajax.Request('/poll', {method: 'get', onSuccess:function(e){
say(e.responseText);
setTimeout(poll, 0);
}});
}
function put() {
var text = $F('msg');
new Ajax.Request('/say?msg=' + encodeURIComponent(text));
$('msg').value = '';
}
poll();
</script>
</head>
<body>
<form action="/say" onsubmit="put(); return false;">
<input type="text" name="msg" id="msg" size="40"></input>
</form>
<div id="chat" style="margin-top:4em">
&nbsp;
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment