我想从 javascript 启动一个长轮询请求,这很好,我希望我的 ruby prog 将多个正文部分流式传输到 javascript。为什么以下(伪)代码不起作用?
require 'rubygems'
require 'sinatra/async'
require 'eventmachine'
require 'thin'
require 'json'
class Test < Sinatra:Base
register Sinatra::Async
aget '/process' do
for c in 1..10
body {
{ :data => [ "this is part #{c}" ] }.to_json
end
end
end
run!
end
也许我误解了长轮询和异步应该做什么,但我的期望是我将多个主体发送回客户端?我需要使用 eventmachine 还是其他东西?
thanks
require 'rubygems'
require 'sinatra/async'
require 'thin'
require 'json'
class Test < Sinatra::Base
register Sinatra::Async
class JSONStream
include EventMachine::Deferrable
def stream(object)
@block.call object.to_json + "\n"
end
def each(&block)
@block = block
end
end
aget '/process' do
puts 'ok'
out = JSONStream.new
body out
EM.next_tick do
c = 0
timer = EM.add_periodic_timer(0.3) do
c += 1
out.stream :data => ["this is part #{c}"]
if c == 100
timer.cancel
out.succeed
end
end
end
end
run!
end
也可以看看:http://confreaks.net/videos/564-scotlandruby2011-real-time-rack
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)