Hi I have code which sets up a basic client to server scenario and exchanges data between them. Basically the server waits for data from the client and, once sent by the client, prints it to the screen.
I have been tasked with getting the length of the data sent. I am a-little confused as to what this means as it could mean the actual length of the data or the total size of the packet sent.
The message is simply Mary.
Now does this mean the packet size would be 4? I have code that gets this like so:
System.out.println( "Packet Length: "+packet.getData().length );
System.out.println( "Data Length: "+message.getBytes().length );
They both return 4. But the maximum data packet size is 65535 so Im wondering if this number should be a lot bigger…
Now with code:
public static void main(String[] args) throws IOException
{
String message = "Mary";
byte[] buf = message.getBytes();
System.out.println("Aclient: message is:" + message);
String serverName = "127.0.0.1";
if (args.length == 1) {
serverName = args[0];
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
InetAddress address = InetAddress.getByName(serverName);
int port = 4441;
DatagramPacket packet = new DatagramPacket(
buf, buf.length, address, port);
System.out.println( "Packet Length: "+packet.getData().length );
System.out.println( "Data Length: "+message.getBytes().length );
System.out.println("Aclient: destination name:" +
address.getHostName() + " destination port:" + port);
System.out.println("Aclient: sending datagram");
socket.send(packet);
}
What you see is the expected behavior.
"Mary".getBytes()returns abyte[]with length 4; that’s 1 byte for each character, which makes sense because it’s nothing but ASCII.Likewise, you’ve told the
DatagramPacketthat you’re sending those same 4 bytes, so it should be no surprise thatDatagramPacket#getData()agrees with …the data you’re asking it to send.Hopefully it makes sense to you that the packet wouldn’t use the full 65535 bytes unless you actually have that much data to send. It’s a maximum, not a minimum, size.