1

我正在学习java.net并尝试制作一个简单的应用程序。这是代码:

编辑:我的错,对不起,但主要问题仍然存在。这是更正的代码:

public static void main(String args[]){
        try{

            Socket s = new Socket("localhost", 3128);
            args[0] = args[0]+"\n"+s.getInetAddress().getHostAddress()
                    +":"+s.getLocalPort();
            s.getOutputStream().write(args[0].getBytes());

            byte buf[] = new byte[64*1024];
            int r = s.getInputStream().read(buf);
            String data = new String(buf, 0, r);

            System.out.println(data);
        } catch(Exception e){
            System.out.println("init error: "+e);
        }
    }

但是当我试图启动它时,它给了我以下错误:

init error: java.lang.ArrayIndexOutOfBoundsException: 0

这可能是什么原因?

UPD:这是其余的跟踪:

/usr/lib/jvm/jdk1.7.0_13/bin/java -Didea.launcher.port=7535 -Didea.launcher.bin.path=/home/mikhail/Загрузки/idea-IU-123.155/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/jdk1.7.0_13/jre/lib/jce.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/jfr.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/deploy.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/rt.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/javaws.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/jfxrt.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/resources.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/jsse.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/management-agent.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/plugin.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/charsets.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/dnsns.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/sunec.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/zipfs.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/localedata.jar:/usr/lib/jvm/jdk1.7.0_13/jre/lib/ext/sunjce_provider.jar:/home/mikhail/bzrrep/DLP/producer/target/classes:/home/mikhail/.m2/repository/commons-lang/commons-lang/2.3/commons-lang-2.3.jar:/home/mikhail/.m2/repository/org/apache/pdfbox/pdfbox/1.8.0/pdfbox-1.8.0.jar:/home/mikhail/.m2/repository/org/apache/pdfbox/fontbox/1.8.0/fontbox-1.8.0.jar:/home/mikhail/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar:/home/mikhail/.m2/repository/org/apache/pdfbox/jempbox/1.8.0/jempbox-1.8.0.jar:/home/mikhail/Загрузки/idea-IU-123.155/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain com.messagedna.dlp.main.Main
4

1 回答 1

2

这可能是什么原因?

的原因ArrayIndexOutOfBoundsException是您没有将任何参数传递给您的程序。因此,args[0]不引用有效的数组索引(顺便说一句:我会创建一个单独的局部变量而不是分配给args[]数组。从技术上讲这是可能的,但我不会考虑这种“好风格”)。

当你向你的程序传递一个参数时,你会得到一个,NullPointerException因为你还没有配置你的 Socket。您至少需要将其连接到某个服务器,例如:

s.connect(new InetSocketAddress("myserver.example.com", 1234));

然后,当在“myserver.example.com”的端口 1234 上运行适当的服务器时,您将能够发送和接收一些数据。

有关 Java 网络编程的更多信息,您应该阅读Sockets 教程

于 2013-07-15T10:58:11.163 回答