Herong's Tutorial Notes on Perl - Part B
Dr. Herong Yang, Version 4.11

RPC::XML Module

Part:   1  2  3  4  

(Continued from previous part...)

RpcXmlServer2.pl - Receiving an Array

A visitor mailed me a sample RPC::XML server program that failed to receive an array from the client. The cause of the problem was related to how an input argument of an array is delivered to the receiving method on the server side. The rule of passing arrays is simple: "All arrays are passed as hard references". Here is the modified sample server program, RpcXmlServer2.pl:

#- RpcXmlServer2.pl
#- Copyright (c) 2005 by Dr. Herong Yang
#
   use RPC::XML;
   use RPC::XML::Server;
   my $host = "localhost";
   my $port = "8001";
   my $daemon = RPC::XML::Server->new(host => $host, port => $port);
#
   print "Adding com.herong.saveArray...\n";
   my $method = RPC::XML::Method->new({
      name      => 'com.herong.saveArray',
      signature => ['string array'],
      code      => \&saveArray});
   $daemon->add_method($method);
#
   print "Listening at $host:$port...\n";
   $daemon->server_loop();

sub saveArray {
   my $s = shift; # The first parameter is the server object
#   my @a = shift; # Here is the mistake of the original program
   my $a = shift; # The array is received as a reference scalar
   my @a = @$a; # Taking the array out of reference 
   open(MYFILE, "> myfile.txt") or die "cannot open the file";
   foreach my $line (@a) {
      print MYFILE "$line\n";
   }
   close MYFILE;
   return "Array saved ok.";
}

As you can see in the saveArray() method, the mistake of the original program is that the input argument is assigned to an array directly. There was no syntax error, but the array would contain only element representing the hard reference of the argument, which is an array. The output file would be a string of "ARRAY(0x...)"

The sample client program is also modified as RpcXmlClient2.pl:

#- RpcXmlClient2.pl
#- Copyright (c) 2005 by Dr. Herong Yang
#
   require RPC::XML;
   require RPC::XML::Client;
   my $client = RPC::XML::Client->new('http://localhost:8001');

   print "\nCalling com.herong.saveArray...\n";
   my $var = RPC::XML::array->new("one", "two");
   my $res = $client->send_request('com.herong.saveArray', $var);
   print "   Response string = ".$res->as_string."\n";
   print "   Response value = ".$res->value."\n";
   
   exit;

If you the server program first, then the client program, you will get the correct data in the output file:

one
two

This sample server program also shows you:

  • How RPC::XML::Method class can be used to create a RPC::XML method object.
  • How RPC::XML::array class can be used to create a RPC::XML array object.

Conclusion

  • RPC::XML is indeed a simple Perl implementation of XML-PRC protocol.
  • RPC::XML passes arrays as hard references.

Part:   1  2  3  4  

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part B - RPC::XML Module