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

时间:2013-07-15 10:33:41

标签: java sockets

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

1 个答案:

答案 0 :(得分:2)

  

这可能是什么原因?

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

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

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

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

有关Java中网络编程的更多信息,您应该查看Sockets tutorial