我正在尝试运行这个GreetingClient程序,但它给了我错误

时间:2014-11-04 09:17:03

标签: java cmd

它给我一个像线程中的异常错误" main" java.lang.ArrayIndexOutOfBoundsException:0 在GreetingClient.main(GreetingClient.java:8)

import java.net.*;
import java.io.*;
public class GreetingClient{
public static void main(String [] args)
 {
 String serverName = args[0];
  int port = Integer.parseInt(args[1]);
  try
  {
  System.out.println("Connecting to " + serverName + " on port " + port);
     Socket client = new Socket(serverName, port);
     System.out.println("Just connected to " + client.getRemoteSocketAddress());
     OutputStream outToServer = client.getOutputStream();
     DataOutputStream out =new DataOutputStream(outToServer);
     out.writeUTF("Hello from "+ client.getLocalSocketAddress());
     InputStream inFromServer = client.getInputStream();
     DataInputStream in = new DataInputStream(inFromServer);
     System.out.println("Server says " + in.readUTF());
     client.close();
  }catch(IOException e)
  {
     e.printStackTrace();
  }
  }
  }

2 个答案:

答案 0 :(得分:2)

你必须用参数启动程序。

java GreetingClient myServer 1337

Here is an official tutorial for that topic

答案 1 :(得分:0)

编译时,您将编写java GreetingClient servername。因此,对您的代码进行以下修改,     String serverName = args [2];     int port = Integer.parseInt(args [3])