Skip to content
This repository
branch: master
file 47 lines (35 sloc) 1.003 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
require 'em-websocket'
# requires the twitter-stream gem
require 'twitter/json_stream'
require 'json'

#
# broadcast all ruby related tweets to all connected users!
#

username = ARGV.shift
password = ARGV.shift
raise "need username and password" if !username or !password

EventMachine.run {
  @channel = EM::Channel.new

  @twitter = Twitter::JSONStream.connect(
    :path => '/1/statuses/filter.json?track=ruby',
    :auth => "#{username}:#{password}",
    :ssl => true
  )

  @twitter.each_item do |status|
    status = JSON.parse(status)
    @channel.push "#{status['user']['screen_name']}: #{status['text']}"
  end


  EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8080, :debug => true) do |ws|

    ws.onopen {
      sid = @channel.subscribe { |msg| ws.send msg }
      @channel.push "#{sid} connected!"

      ws.onmessage { |msg|
        @channel.push "<#{sid}>: #{msg}"
      }

      ws.onclose {
        @channel.unsubscribe(sid)
      }
    }

  end

  puts "Server started"
}
Something went wrong with that request. Please try again.