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: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 !";
}
}
服务端程序,用于执行任务 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();
}
}
}
服务器端主程序,用于绑定接口 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]