Reputation:
I'm trying to receive data from a client and then log it onto the console. Here is how i do this:
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 last one, and reprinting it with a newer one.
I've figured out what is the problem though.
If i put allocation of the array data
inside the while
loop, everything works fine and i don't get the previous message again, just current one.
I don't really want to do this, because allocation inside loops not a good idea so i need somehow to clear my array before new data comes in.
The output without allocation inside the loop is:
Console: past message
Console: (imagine i typed hello) hellomessage
and so on.
Upvotes: 5
Views: 78
Reputation: 23644
Create the packet outside of the loop, and also retrieve size data from the packet. (Otherwise you'll print the entire array which could contain the trailing 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());
...
Upvotes: 2