//接口
package cn.wsl.rmi.server;
import java.io.IOException;
import java.util.Date;
public interface Hello {
public String echo(String msg) throws IOException;
public Date getTime_r() throws Exception;
}
//create remote interface
package cn.wsl.rmi.server;
import java.rmi.Remote;
public interface HelloService extends Remote, Hello {
}
//create remote class
package cn.wsl.rmi.server;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;
public class HelloServiceImpl implements HelloService {
private String name;
public HelloServiceImpl(String name) throws RemoteException {
this.name = name;
UnicastRemoteObject.exportObject(this, 0);// 把自身对象导出为远程对象,0是随机监听的端口,其他数字为指定的
}
@Override
public String echo(String msg) throws RemoteException {// RemoteException
// is IOException `s
// subclass
System.out.println(name + " echo() method;");
return "echo " + name;
}
@Override
public Date getTime_r() throws RemoteException {// RemoteException is
// Exception `s subclass
System.out.println(name + ": invoke getTime_r() method;");
return new Date();
}
}
//create server program
package cn.wsl.rmi.server;
import javax.naming.Context;
import javax.naming.InitialContext;
public class SimpleServer {
public static void main(String[] args) {
try {
HelloService hello1 = new HelloServiceImpl("hello1");// create
// romte
// object
HelloService hello2 = new HelloServiceImpl("hello2");
Context nameContext = new InitialContext();
nameContext.rebind("rmi:hello1", hello1);// 注册远程对象,注册名字 以 rmi 开头
nameContext.rebind("rmi:hello2", hello2);// rebind方法默认绑定到1099端口、、
System.out.println("bind succes!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//create client program
package cn.wsl.rmi.client;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import cn.wsl.rmi.server.HelloService;
public class SimpleClient {
public static void showRemoteObjects(Context namingContext)
throws Exception {
NamingEnumeration<NameClassPair> e = namingContext.list("rmi:");
while (e.hasMore()) {
System.out.println(e.next(). getName_r());
}
}
public static void main(String args[]) {
String url = "rmi://localhost/";
try {
Context namingContext = new InitialContext();
HelloService hello1 = (HelloService) namingContext.lookup(url
+ "hello1");
HelloService hello2 = (HelloService) namingContext.lookup(url
+ "hello2");
Class stubClass = hello1. getClass_r();
System.out.println("hello1 : " + stubClass. getName_r());
Class[] interfaces = stubClass. getInterfaces_r();
for (int i = 0; i < interfaces.length; i++) {
System.out.println("interfaces : " + interfaces[i]. getName_r());
}
System.out.println(hello1.echo("hello "));
System.out.println(hello1. getTime_r());
System.out.println(hello2.echo("hello "));
System.out.println(hello2. getTime_r());
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行

结果

此文章由 http://www.ositren.com 收集整理 ,地址为:
http://www.ositren.com/htmls/70358.html