sub new { my $class = shift; my %args = @_; die "Usage: Net::Twitter::Stream->new ( user => 'user', pass => 'pass', callback => \&got_tweet_cb )" unless $args{user} && $args{pass} && $args{callback}; my $self = bless {}; $self->{user} = $args{user}; $self->{pass} = $args{pass}; $self->{got_tweet} = $args{callback}; $self->{connection_closed} = $args{connection_closed_cb} if $args{connection_closed_cb}; my $content = "follow=$args{follow}" if $args{follow}; $content = "track=$args{track}" if $args{track}; $content = "follow=$args{follow}&track=$args{track}\r\n" if $args{track} && $args{follow}; my $auth = encode_base64 ( "$args{user}:$args{pass}" ); chomp $auth; my $cl = length $content; my $req = <new ( PeerAddr => 'stream.twitter.com:https' ); $sock->print ( "$req$content" ); while ( my $l = $sock->getline ) { last if $l =~ /^\s*$/; } while ( my $l = $sock->getline ) { next if $l =~ /^\s*$/; # skip empty lines $l =~ s/[^a-fA-F0-9]//g; # stop hex from compaining about \r my $jsonlen = hex ( $l ); last if $jsonlen == 0; eval { my $json; my $len = $sock->read ( $json, $jsonlen ); my $o = from_json ( $json ); $self->{got_tweet} ( $o, $json ); }; } $self->{connection_closed} ( $sock ) if $self->{connection_closed}; }