This section provides a tutorial example on how to write a RPC::XML server sample program, RpcXmlServer.pl, supporting 3 remote methods: com.herong.hello, com.herong.getCelsius, and com.herong.getInfo.
To test RPC::XML, I wrote the following the sample server program,
RpcXmlServer.pl:
#- RpcXmlServer.pl
#- Copyright (c) 2005 by Dr. Herong Yang, http://www.herongyang.com/
#
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.hello...\n";
$daemon->add_method({ name => 'com.herong.hello',
signature => ['string'],
code => sub {return "Hello world!";} });
#
print "Adding com.herong.getCelsius...\n";
my @sig = ('double', 'double double');
$daemon->add_method({ name => 'com.herong.getCelsius',
signature => \@sig, code => \&getCelsius });
#
print "Adding com.herong.getInfo...\n";
$daemon->add_method({ name => 'com.herong.getInfo',
signature => ['array'], code => \&getInfo });
#
print "Listening at $host:$port...\n";
$daemon->server_loop();
#
sub getCelsius {
my $s = shift; # The first parameter is the server object
my $f = shift;
$f = 0.0 unless $f;
print "getCelsius called with ".$f."...\n";
return ($f-32.0)/1.8;
}
#
sub getInfo {
my @info = ("Author","Herong Yang", "Version", "2005");
return \@info;
}
Of course, this is a very simple XML-RPC server:
It offers 3 methods: com.herong.hello, com.herong.getCelsius, and
com.herong.getInfo.
com.herong.hello has one signature: return type of string, and no input
argument. Its handler function is defined inside the add_method call.
com.herong.getCelsius has two signatures. The first one requires no input
argument, and the second one requires one "double" argument.
com.herong.getInfo has one signature of returning an 'array'. The corresponding
handler function returns a reference to a list. The server knows how to convert
the content of the reference to an 'array'.
If you run the RpcXmlServer.pl in a command window, you will see:
Adding com.herong.hello...
Adding com.herong.getCelsius...
Adding com.herong.getInfo...
Listening at localhost:8001...