apache的xml-rpc(Demo实例)

来源:互联网 发布:谷歌算法 编辑:程序博客网 时间:2024/06/10 22:02

RPC是Remote Procedure Call(远程过程调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为“分布式计算”,是为了提高各个分立机器的“互操作性”而发明出来的技术。

首先来看一个小的实例,如下:

服务器端的代码如下:

import org.apache.xmlrpc.server.PropertyHandlerMapping;import org.apache.xmlrpc.server.XmlRpcServer;import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;import org.apache.xmlrpc.webserver.WebServer;public class Server {    private static final int port = 9999;    public static void main(String[] args) throws Exception {        WebServer webServer = new WebServer(port);           XmlRpcServer xmlRpcServer = webServer.getXmlRpcServer();           PropertyHandlerMapping phm = new PropertyHandlerMapping();        phm.addHandler("Calculator", Calculator.class);        xmlRpcServer.setHandlerMapping(phm);        XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig();        serverConfig.setEnabledForExtensions(true);        serverConfig.setContentLengthOptional(false);        webServer.start();    }}class Calculator {    public int add(int i1, int i2) {            return i1 + i2;    }    public int subtract(int i1, int i2) {            return i1 - i2;    }}
客户端的代码如下:

import java.net.URL;import org.apache.xmlrpc.client.XmlRpcClient;import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;public class Client {    public static void main(String[] args) throws Exception {        // create configuration        XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();        config.setServerURL(new URL("http://localhost:9999/xmlrpc"));        config.setEnabledForExtensions(true);          config.setConnectionTimeout(60 * 1000);        config.setReplyTimeout(60 * 1000);                XmlRpcClient client = new XmlRpcClient();        client.setConfig(config);        Object[] params = new Object[]{new Integer(5), new Integer(3)};        Integer result = (Integer) client.execute("Calculator.add", params);               System.out.println("result : "+result);    }}
先启动Server,后启动Client。输出的结果为8。





0 0
原创粉丝点击