package cn.com.wlz.rmi;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* 远程接口
* @author Administrator
*
*Remote 接口用于标识其方法可以从非本地虚拟机上调用的接口。
*任何远程对象都必须直接或间接实现此接口。
*只有在“远程接口”(扩展 java.rmi.Remote 的接口)
*中指定的这些方法才可远程使用。
*
*/
public interface IHello extends Remote {
public String sayHello( String name ) throws RemoteException ;
}
package cn.com.wlz.rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* title:远程实现类 UnicastRemoteObject:建立服务端与客户之间的连接
* 在Hello的构造函数中调用super();初始化UnicastRemoteObject类
* 所有的方法throws RemoteException
* @author Administrator
*
*/
public class Hello extends UnicastRemoteObject implements IHello,java.io.Serializable {
public Hello() throws RemoteException {
super();
}
public String sayHello( String name ) throws RemoteException {
return "Hello:"+name;
}
}
package cn.com.wlz.rmi;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* title:title:在指定的上下文通过JNDI绑定指定的对像。
* 客户端通过JNDI名字可获取对像,并调用其方法
* @author Administrator
*
*/
public class Server {
public static void main( String args[] ){
System.out.println( "server star............" );
//设置上下文
Hashtable env = new Hashtable();
//初始化上下文
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory" );
//指定URL
env.put( Context.PROVIDER_URL, "rmi://192.168.1.101:8888" );
try {
//注册RMI
LocateRegistry.createRegistry( 8888 );
//创建远程的实现类
IHello h = new Hello();
//把h对象通过JNDI绑定
Context context = new InitialContext( env );
//绑定
context.rebind( "hello", h );
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package cn.com.wlz.rmi;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class Client {
public static void main( String args[] ){
System.out.println( "server star............" );
//设置上下文
Hashtable env = new Hashtable();
//初始化上下文
env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory" );
//指定URL
env.put( Context.PROVIDER_URL, "rmi://192.168.1.101:8888" );
try {
//把对象通过JNDI绑定
Context context = new InitialContext( env );
//在当前指定的上下文中,通过JNDI的名字去查找指定的对像
IHello hello = (IHello) context.lookup( "hello" );
System.out.println("远程方法调用"+hello.sayHello( "wlz" ));
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}