Created
October 10, 2009 21:19
-
-
Save youpy/207140 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 'sinatra' | |
# doesn't work on thin and webrick | |
set :server, 'mongrel' | |
get '/' do | |
<<HTML | |
<html> | |
<head> | |
<title>Server Push</title> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> | |
<script src="/js/server_push.js"></script> | |
</head> | |
<body> | |
<h1>Server Push</h1> | |
<div id="content"></div> | |
</body> | |
</html> | |
HTML | |
end | |
get '/js/server_push.js' do | |
<<JS | |
$(function() { | |
var xhr = new XMLHttpRequest(); | |
xhr.multipart = true; | |
xhr.onreadystatechange = function() { | |
// 1->2->3->4->1->... | |
$('#content').append("<p>readyState: " + xhr.readyState + "</p>"); | |
if(xhr.readyState == 4) { | |
$('#content').append(xhr.responseText); | |
} | |
}; | |
xhr.open("GET", "/push"); | |
xhr.send(null); | |
}); | |
JS | |
end | |
get '/push' do | |
boundary = 'ThisRandomString' | |
response['Content-Type'] = 'multipart/x-mixed-replace;boundary=' + boundary | |
PushResponse.new(boundary, 'text/plain', 3) do | |
"<p>#{rand.to_s}</p>" | |
end | |
end | |
class PushResponse | |
def initialize(boundary, content_type, interval, &block) | |
@boundary = boundary | |
@content_type = content_type | |
@interval = interval | |
@block = block | |
end | |
def each | |
yield "--#{@boundary}\n" | |
loop do | |
yield "Content-Type: #{@content_type}\n\n" + @block.call + "\n--#{@boundary}\n" | |
sleep @interval | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment