运维开发网

ruby – 使用异步sinatra流多个身体

运维开发网 https://www.qedev.com 2020-08-09 22:23 出处:网络 作者:运维开发网整理
我想从 javascript开始一个很长的轮询请求,这很好,我希望我的ruby prog将多个body部分流式传输到javascript.为什么以下(伪)代码不起作用? require 'rubygems' require 'sinatra/async' require 'eventmachine' require 'thin' require 'json' class Test < S
我想从 javascript开始一个很长的轮询请求,这很好,我希望我的ruby prog将多个body部分流式传输到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吗?

谢谢

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

0

精彩评论

暂无评论...
验证码 换一张
取 消