Problem with Simple TimeServer app using UDP

We have a Server setup in my Distributed apps class which we are meant to write a client program that sends a DatagramPacket to the server and then receives back a packet that has the time and date. We seem to be doing everything correctly but the behavior we are receiving is not what we want. We send a packet that has a 512 byte buffer, and receive back data of length 512 bytes, we then try to make that buffer a string and then simply display it. Here is what we have:

my Declarations:

......

private DatagramSocket socket;

private byte[] data;

private DatagramPacket packet;

.....

Constructor:

....

address = InetAddress.getByName(ipTextField.getText());

try{

socket = new DatagramSocket();

packet = new DatagramPacket(data,512,address,port);

//socket.connect(address, port);

}catch(IOException e){};

.......

//THIS IS WHERE THE ACTUAL WORK IS PERFORMED//

public void actionPerformed(ActionEvent e){

if(e.getSource()==goButton){

try{

socket.send(packet);

byte[] buffer = new byte[512];

DatagramPacket receivePacket = new DatagramPacket(buffer,512);

socket.receive(packet);

buffer = packet.getData();

String date = new String(buffer);

System.out.println("buffer: " + date);

addressInformation.setText(date);

}catch(IOException ex){System.out.println("Error" + ex);};

}

}

This is what the System.out.println fo the date gives us:

buffer: Fri Feb 09 11:59:05 CST 2007[FROM HERE ON IS JUNK CHARACTERS REPEATING]

The GUI output is nothing but the square ascii character, no date is shown (this might be because it is filled with these squares).

[1750 byte] By [m1keclancya] at [2007-11-26 17:57:20]
# 1

You're almost there. A UDP packet contains a fixed length buffer, but the data does not necessarily fill the entire buffer. See the [url http://java.sun.com/j2se/1.5.0/docs/api/java/net/DatagramPacket.html]API documentation[/url] to see the methods needed to get both the offset and the length of the received data. Once you know the offset and length, use the correct String constructor to create a String.

Jasprea at 2007-7-9 5:10:33 > top of Java-index,Desktop,Core GUI APIs...