0

我有三个java文件一个是RMI服务器和RMI客户端和接口文件,如下:服务器:

import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.net.*;

public class RmiServer extends 
  java.rmi.server.UnicastRemoteObject implements ReceiveMessageInterface{
  String address;
  Registry registry; 

  public void receiveMessage(String x) throws RemoteException{
  System.out.println(x);
  }
  
  public RmiServer() throws RemoteException{
  try{  
  address = (InetAddress.getLocalHost()).toString();
  }
  catch(Exception e){
  System.out.println("can't get inet address.");
  }
  int port=3233; 
  System.out.println("this address=" + address +  ",port=" + port);
  try{
  registry = LocateRegistry.createRegistry(port);
  registry.rebind("rmiServer", this);
  }
  catch(RemoteException e){
  throw e;
  }
  }
  static public void main(String args[]){
  try{
  RmiServer s = new RmiServer();
  }
  catch (Exception e){
  e.printStackTrace();
  System.exit(1);
  }
  }
}

客户:

import java.rmi.*;
import java.rmi.registry.*;

import java.net.*;

public class RmiClient{
  static public void main(String args[]){
  ReceiveMessageInterface rmiServer;
  Registry registry;
  String serverAddress=args[0];
  String serverPort=args[1];
  String text=args[2];
  System.out.println
   ("sending " + text + " to " +serverAddress + ":" + serverPort);
  try{
  registry=LocateRegistry.getRegistry
  (serverAddress,(new Integer(serverPort)).intValue());
  rmiServer=(ReceiveMessageInterface)(registry.lookup("rmiServer"));
  // call the remote method
  rmiServer.receiveMessage(text);
  }
  catch(RemoteException e){
  e.printStackTrace();
  }
  catch(NotBoundException e){
  e.printStackTrace();
  }
  }
}

界面:

import java.rmi.*;

public interface ReceiveMessageInterface extends Remote{
  void receiveMessage(String x) throws RemoteException;
}

所以基本上,当我运行服务器时,它会给我的笔记本电脑地址和正在运行的端口,这工作得很好但是,问题是当我运行服务器后运行客户端时,它会不断抛出这个错误:

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:索引 0 超出长度 0 的范围

此行中的哪个客户端文件:

String serverAddress=args[0];
4

2 回答 2

2

如果您查看方法“static public void main(String args[])”,String args[] 是一个标准约定。当您以您使用的方式调用程序时,您应该在命令行中将值传递给该数组。

您出现异常的原因是,您的数组中没有 args[0] ,因为您没有传递值。当您在程序中访问 args[0]、args[1] 和 args[2] 时,请确保在调用程序时通过命令行传递三个值。

例子 :

public class X{
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

如何运行

java X a ab abc

预期结果

一个

抗体

美国广播公司

于 2021-05-07T07:06:23.680 回答
0

由于没有传递给 main 方法的参数值,这就是它抛出错误的原因。

我相信您没有将命令行参数分配给 main 方法。如果您使用任何 IDE 运行项目,请搜索如何在项目执行期间传递参数。

在这里您可以找到如何为 Netbeans IDE 配置参数 - Netbeans 如何在 Java 中设置命令行参数

如果您正在使用任何其他 IDE,那么类似地搜索它。

否则,您可以通过命令提示符运行来简单地为程序提供命令行参数。

于 2021-05-07T06:22:50.820 回答