我试图在使用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'应该可以工作。 –