我試圖在使用Sinatra時使用Twitter流媒體API並在用戶搜索關鍵字時爲用戶提供實時更新。一旦連接關閉,如何在Sinatra中停止後臺線程
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流。有誰知道如何做到這一點?
我剛剛爲Sinatra添加了多重回調支持,因此在下一個Sinatra版本中,此示例不再需要sinatra-contrib。 –
該回調確實有效,但em-http-request不響應關閉或取消綁定(例如http.close)。有任何想法嗎? – aciniglio
'http.conn.close_connection'應該可以工作。 –