EventMachine和Twitter流媒体API

tom*_*oft 5 ruby twitter eventmachine http-streaming

我正在使用Twitter流API运行EventMachine流程.如果流的内容不频繁,我总是有问题.

这是脚本的最小版本:

require 'rubygems'
require 'eventmachine'
require 'em-http'
require 'json'

usage = "#{$0} <user> <password> <track>"
abort usage unless user = ARGV.shift
abort usage unless password = ARGV.shift
abort usage unless keywords= ARGV.shift

def startIt(user,password,keywords)
EventMachine.run do
  http = EventMachine::HttpRequest.new("https://stream.twitter.com/1/statuses/filter.json",{:port=>443}).post(
                    :head =>{ 'Authorization' => [ user, password ] } , 
                    :body =>{"track"=>keywords},
                    :keepalive=>true,
                    :timeout=>-1)

  buffer = ""
  http.stream do |chunk|
    buffer += chunk
    while line = buffer.slice!(/.+\r?\n/)
      if line.length>5
          tweet=JSON.parse(line)
          puts Time.new.to_s+"#{tweet['user']['screen_name']}: #{tweet['text']}"
      end
    end

  end
   http.errback {
        puts Time.new.to_s+"Error: "
        puts http.error
   }
end  
    rescue => error
      puts "error rescue "+error.to_s
end

while true
    startIt user,password,keywords
end
Run Code Online (Sandbox Code Playgroud)

如果我搜索像"iphone"这样的关键字,一切都运行正常如果我搜索一个不太常用的关键字,我的流将在最后一条消息后大约20秒后非常快速地关闭.注意:http.error总是空的,所以当流关闭时很难理解......另一方面,神经类似的p​​hp版本没有关闭,所以似乎与eventmachine/http-em有关但是我不明白哪一个......

Chr*_*ris 6

您应该添加设置以防止连接超时.试试这个 :

http = EventMachine::HttpRequest.new(
  "https://stream.twitter.com/1/statuses/filter.json",
  :connection_timeout => 0,
  :inactivity_timeout => 0
).post(
  :head => {'Authorization' => [ user, password ] } , 
  :body => {'track' => keywords}
)
Run Code Online (Sandbox Code Playgroud)

祝你好运,基督徒