public
Created

  • Download Gist
chat.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
require 'java'
require 'atmosphere-spade-server.jar'
 
include_class 'javax.servlet.http.HttpServlet'
include_class 'org.atmosphere.cpr.AtmosphereHandler'
include_class 'org.atmosphere.grizzly.AtmosphereSpadeServer'
 
#setup and start the server
def main
AtmosphereSpadeServer.build("http://localhost:8080/").addAtmosphereHandler("", ChatPage.new()).addAtmosphereHandler("/chat-stream", ChatStream.new()).start
end
 
 
#serve the chat page
class ChatPage
include AtmosphereHandler
 
def onRequest(event)
Kernel.load(__FILE__)
res = event.getResponse()
 
res.setContentType("text/html")
res.addHeader("Cache-Control", "private")
res.addHeader("Pragma", "no-cache")
File.open(File.dirname(__FILE__)+'/chat.html').each { |line|
res.getWriter().write(line)
}
res.getWriter().flush()
event
end
end
 
#serve the chat stream and post messages
class ChatStream
include AtmosphereHandler
 
def onEvent(event)
#reload the source so we can work on it
#Kernel.load(__FILE__)
req = event.getRequest();
res = event.getResponse();
 
res.setContentType("text/html")
res.addHeader("Cache-Control", "private")
res.addHeader("Pragma", "no-cache")
res.setCharacterEncoding("UTF-8");
 
if (req.getMethod().upcase === "GET")
# for IE
res.getWriter().write("<!-- Comet is a programming technique that enables web " +
"servers to send data to the client without having any need " +
"for the client to request it. -->\n");
res.getWriter().flush();
event.suspend();
 
elsif (req.getMethod().upcase === "POST")
message = req.getParameterValues("message")[0].to_s
ip = req.getRemoteAddr().to_s
#if (rand()*3).to_i == 2
# message = message.gsub(/[^aeiou]/, '*')
#end
 
event.getBroadcaster().broadcast(
"<script>window.parent.say('<small>#{ip} - #{req.getHeader("User-Agent").to_s}:</small><br><b>#{message}</b>')</script>")
 
res.getWriter().write('success')
res.getWriter().flush();
end
 
event
end
 
def onMessage(event)
writer = event.getResponse().getWriter()
writer.write(event.getMessage().to_s.ljust(1*1024))
writer.flush()
event
end
end
 
 
 
if !$once
main
$once = true
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.