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.
user6866343
source share