将多个客户端连接到服务器:ArrayIndexOutOfBoundsException:0

Connecting more than one Client to server: ArrayIndexOutOfBoundsException: 0

希望你能帮我解决我的问题。

我有一个 ServerClass 和一个 ClientClass,我可以连接这两个程序。但是如果我想通过同一台虚拟机将多个客户端连接到我的服务器,我会收到以下错误:java.lang.ArrayIndexOutOfBoundsException: 0

我向我的程序传递了一个命令行参数!

但我不知道为什么...这是对我的问题很重要的部分:

public class ClientStart {
[...]

    public static void main(String[] args) {
        System.out.print("Geben Sie Ihre IP-Adresse ein: ");
        ipadress = readString();
        args[0] = ipadress;
        System.out.println("");
        if (args.length != 1) {
            System.exit(1);
        }
        connect();
        ipadress = "";
    }

    public static void connect() {
        InetSocketAddress inetSocketAddress
                = new InetSocketAddress(ipadress, 56789);
[...]

谢谢!

main方法中的args[]是程序执行时传递的参数。您不能使用 args[0],因为程序是在没有参数的情况下调用的,并且数组是空的。

只需使用您在 ipadress 中读取的值,不要尝试将其分配给 args[0]。如果您提供更多代码,我会更有帮助。

args[0] = ipadress; // Args here is an empty array - you don't need that line

args 是一个数组,其长度在初始化期间确定(与任何其他数组一样)。

在你的情况下,可能因为你没有向你的程序传递任何参数,它的大小为零,因此

args[0] = ipadress;

抛出 IndexOutOfBoundsException 因为数组的长度为零。