[JDEV] "who is online?" with Net::Jabber

Ralph Siemsen ralphs at blueairnetworks.com
Thu Jan 30 11:23:27 CST 2003


Stefan Strigler wrote:

> Sure I am. I don't need to use Net::Jabber. I just thought of an elegant
> way to handle the reply cause I don't want to parse the XML returned
> myself if I don't need to. But its not a big problem if I do it myself
> :)

Ah, I see.  I found Jabber::Connection simpler to use that Net::Jabber, 
but its just personal preference.  They can both do the job.  And you 
are right, it's no fun parsing the XML by hand.  Jabber::Connection (and 
the associated Jabber::NodeFactory) also allow convenient parsing.

Here's the code:

#!/usr/bin/perl -w

use strict;
use Jabber::Connection;
use Jabber::NodeFactory;

# Connections settings
my $host = 'jabber.org';
my $user = 'admin';
my $pass = 'adminpasswd';
my $resource = 'someresource';

# Get connected to server
my $c = new Jabber::Connection(server => $host) or die;
$c->connect or die $c->lastError;
$c->auth($user, $pass, $resource) or die $c->lastError;
print "Connected as $user\@$host/$resource\n";

# Build the packet to be sent
my $iq = new Jabber::NodeFactory::Node('iq');
$iq->attr('to', $host);
$iq->attr('type', 'get');
my $query = $iq->insertTag('query', 'jabber:iq:admin');
$query->insertTag('who');

# Send packet and wait for reply
my $result = $c->ask($iq);
print "Result is: ", $result->toStr, "\n";

# Disconnect
$c->disconnect();


Some notes.

1) If you prefer, instead of building the packet piece-by-piece, you can 
just put it in a string.  Eg. $packet = "<iq to='blah' from='blah><query
and so on.  Then pass that to the ask() method.  If you want to do this, 
you have to say "use Jabber::NodeFactory(fromstr=>1)" at the top. 
Meaning you have to add the "(fromstr=>1)" part.

2) Instead of just printing the resulting XML packet you probably want 
to process the elements.  You can get them by doing this:

   foreach ($result->getTag('query')->getTag('who')->getChildren()) {
       my $jid = $_->attr('from'), "\n";
       # Now do something with $jid
   }

Hope this helps
-R




More information about the JDev mailing list