一旦连接关闭,如何在Sinatra中停止后台线程

时间:2011-10-03 00:10:13

标签: ruby sinatra eventmachine

我正在尝试使用Sinatra的twitter流API,并在搜索关键字时为用户提供实时更新。

require 'sinatra'
require 'eventmachine'
require 'em-http'
require 'json'

STREAMING_URL = 'https://stream.twitter.com/1/statuses/sample.json'

get '/' do
  stream(:keep_open) do |out|
    http = EM::HttpRequest.new(STREAMING_URL).get :head => { 'Authorization' => [ 'USERNAME', 'PASS' ] }
    buffer = ""
    http.stream do |chunk|
      puts "still chugging"
      buffer += chunk
      while line = buffer.slice!(/.+\r?\n/)
        tweet = JSON.parse(line)
        unless tweet.length == 0 or tweet['user'].nil?
            out << "<p><b>#{tweet['user']['screen_name']}</b>: #{tweet['text']}</p>" 
        end
      end
    end
  end
end

如果用户关闭连接,我希望停止处理em-http-request流。有谁知道怎么做?

2 个答案:

答案 0 :(得分:5)

Eric的答案很接近,但它的作用是在你的Twitter流关闭后关闭响应主体(不是客户端连接,顺便说一句),这通常不会发生。这应该有效:

require 'sinatra/streaming' # gem install sinatra-contrib
# ...

get '/' do
  stream(:keep_open) do |out|
    # ...
    out.callback { http.conn.close_connection }
    out.errback { http.conn.close_connection }
  end
end

答案 1 :(得分:0)

我对Sinatra流API还不太熟悉,但你试过这个吗?

http.callback { out.close }