Hi,
i've a problem with my codes, when ever i run it, i got an error from the checking i implemented. Can some pls explain why does the error keep coming.

import java.net.*;
import java.io.*;


public class EchoClient{
   
 static final int serverPort = 1026;
 static final int packetSize = 1024;
   
 @SuppressWarnings("deprecation")
public static void main(String args[]) throws  UnknownHostException, SocketException{
 DatagramSocket socket; //How we send packets
 DatagramPacket packet; //what we send it in
 InetAddress address; //Where to send
 String messageSend; //Message to be send
 String messageReturn; //What we get back  from the Server
 byte[] data;
       
 //Checks for the arguments that sent to  the java interpreter
 // Make sure command line parameters correctr
       
 if(args.length != 2)
 {
 System.out.println("Usage Error : Java EchoClient < Server name> < Message>");
 System.exit(0);
 }   
       
 // Gets the IP address of the Server
 address = InetAddress.getByName(args[0]);
 socket = new DatagramSocket();
               
 data = new byte[packetSize];
 messageSend = new String(args[1]);
 messageSend.getBytes (0,messageSend.length(),data,0);
// messageSend.getBytes(0, messageSend.length(), data, 0);            
 // remember datagrams hold bytes
 packet = new DatagramPacket(data,data.length,address,serverPort);
 System.out.println(" Trying to Send the packet ");
               
 try
 {
  // sends the packet
               
  socket.send(packet);
           
  }
  catch(IOException ie)
  {
  System.out.println("Could not Send :"+ie.getMessage());
  System.exit(0);
  }            
       
  //packet is reinitialized to use it for recieving
       
  packet = new DatagramPacket(data,data.length);
               
  try
  {
  // Receives the packet from the server
                   
  socket.receive(packet);   
               
  }
  catch(IOException iee)
  {
  System.out.println("Could not receive :  "+iee.getMessage() );
  System.exit(0);
  }       
       
  // display message received
       
  messageReturn = new String (packet.getData(),0);
  System.out.println("Message Returned : "+
  messageReturn.trim());
  }    // main
   
   
 } // Class EchoClient

Recommended Answers

All 3 Replies

Exactly what error do you get from which statement?

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at EchoClient.main(EchoClient.java:33)
from line 22.

Based on what you have posted, EchoClient.java:33 is
messageSend = new String(args[1]);
which cannot generate the exception you describe, so please post the code that corresponds to the error message.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.