stream multiple body using async sinatra

后端 未结 2 573
萌比男神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

    0 讨论(0)
  • 2020-12-29 17:36

    It appears in the example below that you need an EventMachine event to trigger the sending of the multiple bodies. Also see this previous answer as well.

    require 'sinatra/async'
    
     class AsyncTest < Sinatra::Base
       register Sinatra::Async
    
       aget '/' do
         body "hello async"
       end
    
       aget '/delay/:n' do |n|
         EM.add_timer(n.to_i) { body { "delayed for #{n} seconds" } }
       end
    
     end
    
    0 讨论(0)
提交回复
热议问题