使用异步西纳特拉流全身多处 [英] stream multiple body using async sinatra
问题描述
我想开始从JavaScript这是一个精致长轮询请求,我希望我的红宝石前卫流身体多个部分给javascript。为什么没有按以下(伪)code的工作?
要求'RubyGems的'
要求西纳特拉/异步
需要'EventMachine的
要求薄
要求JSON 一流的测试与LT;西纳特拉:基本
注册西纳特拉::异步 皮亚杰'/进程的做
在1..10Ç
身体 {
{:数据=> [这部分#{c}里]} .to_json
结束
结束
结束 跑!
结束
也许我误解了应该怎样长轮询和异步做的,但我的期望是,我得到发送回客户端的多个机构?我是否需要使用EventMachine的还是怎么了?
感谢
要求'RubyGems的'
要求西纳特拉/异步
要求薄
要求JSON一流的测试与LT;西纳特拉::基地
注册西纳特拉::异步 类JSONStream
包括EventMachine的::可延迟 DEF流(对象)
@ block.call object.to_json +\\ n
结束 每个高清(安培;块)
@block =块
结束
结束 皮亚杰'/进程的做
把OK
OUT = JSONStream.new
体而出
EM.next_tick做
C = 0
定时器= EM.add_periodic_timer(0.3)做
C + = 1
out.stream:数据=> [这部分#{c}里]
如果c == 100
timer.cancel
out.succeed
结束
结束
结束
结束 跑!
结束
参见:<一href=\"http://confreaks.net/videos/564-scotlandruby2011-real-time-rack\">http://confreaks.net/videos/564-scotlandruby2011-real-time-rack
I would like start a long poll request from javascript which is fine and i expect my ruby prog to stream multiple body sections to the javascript. Why doesn the following (pseudo)code work?
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
Maybe i misunderstood what long polling and async is supposed to do, but my expectation is that i get multiple bodies sent back to the client ? Do i need to use eventmachine or something?
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
See also: http://confreaks.net/videos/564-scotlandruby2011-real-time-rack
这篇关于使用异步西纳特拉流全身多处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!