端口已在使用异常,java rmi使用cmd

voase2hg  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(409)

使用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);
        }
    }
}

为了清晰起见,我在两个不同的项目中将服务器和客户机类分开

rur96b6h

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 (正在运行)

相关问题