RMI是Java平台实现远程调用的规范,下面是一个小例子,本机测试通过
一共有三个java类,远程接口,服务端程序,客户端程序
远程接口:
imp ort java.rmi.*;
public interface HelloIn extends java.rmi.Remote{
String sayHello() throws RemoteException;
}
服务端程序:
imp ort java.rmi.*;
imp ort java.net.*;
imp ort java.rmi.registry.*;
imp ort java.rmi.server.*;
public class Hello extends java.rmi.server.UnicastRemoteObject implements HelloIn{
public Hello() throws RemoteException{
super();
}
public String sayHello() throws RemoteException{
return "Hello,World!";
}
public static void main(String[] args){
//System.setSecurityManager(new java.rmi.RMISecurityManager());
try{
Hello h=new Hello();
java.rmi.Naming.rebind("hello",h);
System.out.print("Ready......");
}
catch(Exception e){
e.printStackTrace();
}
}
}
执行服务端程序前在命令行方式下启动rmi的注册程序: start rmiregistry
客户端程序:
imp ort java.rmi.*;
imp ort java.rmi.registry.*;
public class Helloworld{
public static void main(String[] args){
//System.setProperty( "java.security.policy", "client.policy" );
//System.setSecurityManager(new java.rmi.RMISecurityManager());
try{
HelloIn hi=(HelloIn)Naming.lookup("//fengl/hello");
for(int i=0;i<10;i++){
System.out.println(hi.sayHello());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
一共有三个java类,远程接口,服务端程序,客户端程序
远程接口:
imp
public interface HelloIn extends java.rmi.Remote{
String sayHello() throws RemoteException;
}
服务端程序:
imp
imp
imp
imp
public class Hello extends java.rmi.server.UnicastRemoteObject implements HelloIn{
public Hello() throws RemoteException{
super();
}
public String sayHello() throws RemoteException{
return "Hello,World!";
}
public static void main(String[] args){
//System.setSecurityManager(new java.rmi.RMISecurityManager());
try{
Hello h=new Hello();
java.rmi.Naming.rebind("hello",h);
System.out.print("Ready......");
}
catch(Exception e){
e.printStackTrace();
}
}
}
执行服务端程序前在命令行方式下启动rmi的注册程序: start rmiregistry
客户端程序:
imp
imp
public class Helloworld{
public static void main(String[] args){
//System.setProperty( "java.security.policy", "client.policy" );
//System.setSecurityManager(new java.rmi.RMISecurityManager());
try{
HelloIn hi=(HelloIn)Naming.lookup("//fengl/hello");
for(int i=0;i<10;i++){
System.out.println(hi.sayHello());
}
}
catch(Exception e){
e.printStackTrace();
}
}
}