How can I erase the contents of an array in Java with security?

I am trying to get data from a client and then register it on the console. Here is how I do it:

private final int MAX_PACKET_SIZE = 1024; private byte[] data = new byte[MAX_PACKET_SIZE]; private void receive() { new Thread(() -> { while (running) { DatagramPacket packet = new DatagramPacket(data, data.length); try { socket.receive(packet); sPort = packet.getPort(); ip = packet.getAddress(); address = ip.toString(); } catch (Exception e) { e.printStackTrace(); } String messageToPrint = new String(packet.getData()); System.out.println(messageToPrint.trim() + " " + address + " | " + sPort); } }).start(); } 

When it comes to printing my messageToPrint , it actually repeats the latter and reprints it with a newer one.

I found out what the problem is.

If I set the selection of the data array inside the while , everything works fine, and I do not get the previous message again, just the current one.

I really don't want to do this because allocating inside loops is not a good idea, so I need to somehow clear my array before new data arrives.

Exit without highlighting inside the loop:

 Console: past message Console: (imagine i typed hello) hellomessage 

etc.

+5
source share
1 answer

Create the package outside the loop, and also retrieve the size data from the package. (Otherwise, you will print the entire array, which may contain the final text of the last message received)

 final DatagramPacket packet = new DatagramPacket(data, data.length); while (running) { try { socket.receive(packet); ... final String messageToPrint = new String( packet.getData(), packet.getOffset(), packet.getLength()); ... 
+2
source

Source: https://habr.com/ru/post/1257398/


All Articles