欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdk1.5 下 rmi的编写

程序员文章站 2024-02-21 17:09:10
...
jdk1.5 自动生成stub 更加方便

接口Hello

package example.hello;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {
String sayHello() throws RemoteException;
}


服务端

package example.hello;

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server implements Hello {

public Server() {}

public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {

try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
Registry registry = LocateRegistry.createRegistry(1078);
registry.bind("server", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

客户端

package example.hello;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {

private Client() {}

public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
//可以用Naming.lookup("rmi://localhost:1078/server");
//来替换下面代码
Registry registry = LocateRegistry.getRegistry(null,1078);
Hello stub = (Hello) registry.lookup("server");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
相关标签: Java