if the last packet size is less than the size of the byte array in which we are reading, then redundant data from previous packet is being appended to it.
No. The problem is that the bytes from the first packet are still contained in the recData
byte array. The subsequent read then overwrites the beginning of the byte array with the contents of the second packet, but the remainder of the array is still filled with the data from the first packet.
The underlying issue is that you are ignoring the actual number of bytes received. You should also be using a FileOutputStream
, not a Writer
. Try this:
class Server
{
public static void main(String args[]) throws IOException
{
...
while(true)
{
DatagramPacket recPacket = new DatagramPacket(recData, recData.length);
serverSocket.receive(recPacket);
System.out.println("\n Packet length: " + recPacket.getLength());
out.write((recPacket.getData(), 0, recPacket.getLength());
System.out.println("\nPacket" + ++i + " written to file\n");
out.flush();
}
}
}