ERROR in my UDPClient Program Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of ERROR in my UDPClient Program without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to run a basic UDPCLient-Server program. When i am compile my UDPClient program its causing the below ERROR. Though my Server one compiled successfully.

Can someone guide what’s going wrong?

ERROR:

UDPClient.java:13: error: cannot find symbol
                                new DatagramPacket(m,m.length(),aHost,serverPort);
                                                      ^
  symbol:   method length()
  location: variable d of type byte[]
1 error

My Code:

import java.net.*;
import java.io.*;
public class UDPClient{
        public static void main(String args[]){
                // args give message contents and server hostname
                DatagramSocket aSocket = null;
                try {
                        aSocket = new DatagramSocket();
                        byte[] m = args[0].getBytes();
                        InetAddress aHost = InetAddress.getByName(args[1]);
                        int serverPort = 6789;
                        DatagramPacket request =
                                new DatagramPacket(m,m.length(),aHost,serverPort);
                        aSocket.send(request);
                        byte[] buffer = new byte[1000];
                        DatagramPacket reply = new DatagramPacket(buffer,buffer.length);
                        aSocket.receive(reply);
                        System.out.println("Reply: " + new String(reply.getData()));
                }
                catch (SocketException e){
                        System.out.println("Socket: " + e.getMessage());
                }
                catch (IOException e){
                        System.out.println("IO: " + e.getMessage());
                }
                finally { if (aSocket != null) aSocket.close(); }
        }
}

Answer

The length of an array in Java is not retrieved through a method (m.length()); it’s just a field (m.length). Thus it should be m.length, not m.length().

We are here to answer your question about ERROR in my UDPClient Program - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji