-
-
Save sr3d/184877 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 '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"> | |
| |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment