小编典典

示例套接字应用程序不起作用

java

我正在研究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

阅读 219

收藏
2020-11-30

共1个答案

小编典典

这可能是什么原因?

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

当您将参数传递给程序时,NullPointerException由于尚未配置Socket ,因此将得到一个。您至少需要将其连接到某些服务器,例如:

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

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

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

2020-11-30