package hello; |
public interface Hello extends java.rmi.Remote { |
//rmi应用程序必须继承自java.rmi.Remote |
String sayHello() throws java.rmi.RemoteException ; |
//定义可以远程调用的接口 |
} |
//server方程序,定义HelloImpl类实现Hello接口: |
package hello; |
import java.rmi.*; |
import java.rmi.server.UnicastRemoteObject; |
public class HelloImpl extends UnicastRemoteObject implements Hello |
//实现Hello接口 |
{ |
private String name; |
public HelloImpl (String s ) throws java.rmi.RemoteException { |
super (); //调用父类的构造函数 |
name = s; |
} |
public String sayHello() throws RemoteException { |
return "Hello world!" ; //实现Hello接口定义的方法 |
} |
public static void main ( String args []) { |
System.setSecurityManager ( new RMISecurityManager() ); |
//设置RMI程序需要的安全策略 |
try { |
HelloImpl obj = new HelloImpl ( "HelloServer" ); |
//生成一个HelloImpl的实例 |
Naming.rebind ( "HelloServer" , obj); |
//将这个实例绑定到一个名字上 |
System.out.println ( "HelloImpl created and bound in the registry to the name HelloServer" ); |
} catch (Exception e) { |
System.out.println ( "HelloImpl.main: an exception occured:" ); |
e.printStackTrace(); //产生异常的话,打印出出错信息 |
} |
} |
} |
//server方生成一个远程对象并和一个可和客户对话的名称"HelloServer"绑定。Client端可以根据该名称寻找相应的远程对象,进而调用其远程方法。 |
//client方程序 |
package hello; |
import java.rmi.*; public class HelloClient { |
public static void main (String args[]) { |
System.setSecurityManager ( new RMISecurityManager() ); |
//设置RMI需要的安全策略 |
try { |
Hello obj = (Hello) Naming.lookup ( "HelloServer" ); |
//从服务端获得一个Hello的远程对象 |
String message = obj.sayHello(); |
//远程调用Hello的方法 |
System.out.println (message); |
//将输出结果打印 |
} catch (Exception e) { |
System.out.println ( "Hello client : an exception occured" ); |
e.printStackTrace(); //若有异常,输出异常信息 |
} |
} |
} |
中级程序员
by: 中国人在美国 发表于:2013-07-31 05:15:16 顶(0) | 踩(0) 回复
好,谢谢分享
回复评论