使用java和cmd运行rmi时。将显示java.rmi.server.exportexception。例外情况是,端口已在使用中。
服务器接口
import java.rmi.*;
public interface AdditionInterface extends Remote {
public int add(int a, int b) throws RemoteException;
}
接口实现
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class AdditionClient {
public static void main(String[] args) {
try {
String host="";
Registry registry = LocateRegistry.getRegistry(host);
AdditionInterface hello = (AdditionInterface) registry.lookup("Addition");
int result = hello.add(9, 2);
System.out.println("Result is: " + result);
} catch (Exception ex) {
System.out.println("HelloClient Exception" + ex);
}
}
}
服务器注册表类
package chapter40;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class AdditionServer {
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry();
AdditionInterface obj = new Addition();
registry.rebind("Addition", obj);
System.out.println("Addition Server is ready");
} catch (Exception ex) {
System.out.println("Addition Server failed" + ex);
}
}
}
客户端程序
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class AdditionClient {
public static void main(String[] args) {
try {
String host="";
Registry registry = LocateRegistry.getRegistry(host);
AdditionInterface hello = (AdditionInterface) registry.lookup("Addition");
int result = hello.add(9, 2);
System.out.println("Result is: " + result);
} catch (Exception ex) {
System.out.println("HelloClient Exception" + ex);
}
}
}
为了清晰起见,我在两个不同的项目中将服务器和客户机类分开
1条答案
按热度按时间rur96b6h1#
我搜索了各种各样的线程,最终得到了一种不同于(但也是我所看到的组合)的工作方式
运行服务器程序(从命令提示符):
将目录更改为服务器的源文件夹
cd c:\Users\Heavenly\workspace\RMIServerSide\src
编译类javac chapter40/*.java
启动rmi注册表start rmiregistry
启动包含main()方法的registry server类。注意代码行略有不同start java -cp . chapter40.AdditionServer
(服务器现在已设置)运行客户端程序
将目录更改为源文件夹
cd c:\Users\Heavenly\workspace\RMIClientSide\src
编译所有类javac chapter40/*.java
3.运行客户端程序java chapter40.AdditionClient
(正在运行)