gpt4 book ai didi

Java:远程方法调用 (RMI)

转载 作者:行者123 更新时间:2023-11-30 09:20:51 26 4
gpt4 key购买 nike

我正在尝试运行简单的 RMI 服务,其中服务器和客户端位于同一台机器上。不幸的是,每次我尝试运行服务器类 时,我都会遇到异常。我将服务器和客户端保存在单独的文件夹中,并将需要的文件复制到客户端。

这些是我采取的步骤:

  1. 将服务器文件所在的文件夹添加到 CLASSPATH。
  2. 启动 rmiregistry。 (据我所知,我不再需要使用 stub 文件更新 stub 文件)
  3. 运行服务器。 <- 异常
  4. 运行客户端。

文件夹层次结构:

服务器 [AddServerIntf.class, AddServerImpl.class, AddServer.class]客户端 [AddServerIntf.class, AddClient.class]

异常

C:\Users\Szymon\Desktop\serwer>java AddServer
Exception: java.rmi.ServerException: RemoteException occurred in server thread;
nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: AddServerIntf

代码

远程接口(interface)

import java.rmi.*;

public interface AddServerIntf extends Remote {
double add(double d1, double d2) throws RemoteException;
}

实现上述接口(interface)的类

import java.rmi.*;
import java.rmi.server.*;

public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf {

public AddServerImpl() throws RemoteException {
}
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
}

创建服务器的类

import java.net.*;
import java.rmi.*;

public class AddServer {
public static void main(String args[]) {

try {
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

客户端

import java.rmi.*;

public class AddClient {
public static void main(String args[]) {
try {
String addServerURL = "rmi://" + args[0] + "/AddServer";
AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL);
System.out.println("1st: " + args[1]);
double d1 = Double.valueOf(args[1]).doubleValue();
System.out.println("2nd: " + args[2]);

double d2 = Double.valueOf(args[2]).doubleValue();
System.out.println("Sum: " + addServerIntf.add(d1, d2));
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}

stub 文件效果类似

C:\Users\Szymon\Desktop\serwer>java AddServer
Exception: java.rmi.ServerException: RemoteException occurred in server thread;
nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: AddServerImpl_Stub

最佳答案

Registry 在其 CLASSPATH 中没有您的远程接口(interface)。恕我直言,最好的解决方案是使用 LocateRegistry.createRegistry() 在服务器 JVM 中运行注册表。

As far as I know I no longer need to make stub file

不正确。请参阅 UnicastRemoteObject 的 Javadoc 的序言。您需要在远程对象的构造函数中提供 super(0) 行以满足那里指定的条件。

关于Java:远程方法调用 (RMI),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com