方兆国 发表于 2013-06-22 16:56

RMI远程调用示例

本帖最后由 方兆国 于 2013-06-22 16:59 编辑

此为RMI接口,由服务器端和客户端调用package com.fangzhaoguo.RMI;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RMIServer extends Remote
{
        public String getString() throws RemoteException;
}

方兆国 发表于 2013-06-22 16:57

本帖最后由 方兆国 于 2013-06-22 16:59 编辑

package com.fangzhaoguo.RMI;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Service extends UnicastRemoteObject implements RMIServer
{
        private static final long serialVersionUID = 1L;

        protected Service() throws RemoteException
        {
                super();
        }

        public String getString()
        {
                return "Hello World !";
        }

}
服务端程序,用于执行任务

方兆国 发表于 2013-06-22 16:59

package com.fangzhaoguo.RMI;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

public class Server
{
        public final static int port = 4321;

        public static void main(String[] args)
        {
                try
                {
                        Service service = new Service();
                        LocateRegistry.createRegistry(port);
                        Naming.rebind("//" + InetAddress.getLocalHost().getHostAddress()
                                        + ":" + port + "/database", service);
                } catch (RemoteException | MalformedURLException | UnknownHostException e)
                {
                        e.printStackTrace();
                }
        }

}
服务器端主程序,用于绑定接口

方兆国 发表于 2013-06-22 17:00

package com.fangzhaoguo.RMI;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

public class Client
{
        public final static String host = "127.0.0.1";
        public final static int port = 4321;

        public static void main(String[] args)
        {
                try
                {
                        RMIServer server = (RMIServer) Naming.lookup("//" + host + ":"
                                        + port + "/database");
                        System.out.println(server.getString());
                } catch (MalformedURLException | RemoteException | NotBoundException e)
                {
                        e.printStackTrace();
                }
        }

}
客户端程序
页: [1]
查看完整版本: RMI远程调用示例