stream multiple body using async sinatra

后端 未结 2 580
萌比男神i
萌比男神i 2020-12-29 17:10

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 (p

2条回答
  •  醉酒成梦
    2020-12-29 17:36

    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

提交回复
热议问题