So I've been asked to create a UDP messaging app. I have two clients that are run from the command line on the same computer, and I am trying to get each client to break out of a while loop when it receives the String "exit"
from the other client, so they both terminate simultaneously.
String input
is created above this code so if this client inputs "exit"
, the while is skipped (This works fine!).
DatagramSocket receiveSocket = new DatagramSocket(8000); //Port 8000
byte[] receiveBuffer = new byte[65508];
while(!input.equals("exit")) {
DatagramPacket packetToReceive = new DatagramPacket(receiveBuffer, receiveBuffer.length);
receiveSocket.receive(packetToReceive);
receiveBuffer = packetToReceive.getData();
String receivedMessage = new String(receiveBuffer);
if(!receivedMessage.equals("exit")) {
System.out.println("A says: " + receivedMessage);
}
else {
input = "exit";
}
}
The problem I have is that I cannot get !receivedMessage.equals("exit")
to equate to false
, even though when I do a System.out.println(receivedMessage)
, I get "exit"
. They look exactly the same but obviously aren't.
I have tried forcing encoding such as...
String receivedMessage = new String(receiveBuffer, "UTF-8");
...but nothing works. I've tried many other combinations of forced encoding, plus converting receivedMessage
to a Byte array, char array etc. to compare, and I've checked for whitespace on either side of receivedMessage
, still nothing.
Any help would be appreciated. It has to be something small I'm missing. Thanks.
There is possibly the problem with the receiveBuffer size. Currently you are sending "exit" in the packet, which is small enough to fit in 65508 bytes. So, the remaining bytes in the receiveBuffer are simply empty or contain special characters. That is why when you receive the packet and get the data into a string, the remaining bytes are also there in the string.
You can either use contains()
instead of equals()
for comparing the string or you can put only the desired bytes containing the actual message into the receiveBuffer. Here is one of the possible way to achieve that:
receiveSocket.receive(packetToReceive);
receiveBuffer = new byte[packetToReceive.getLength()];
System.arraycopy(packetToReceive.getData(), packetToReceive.getOffset(), receiveBuffer, 0, packetToReceive.getLength());
String receivedMessage = new String(receiveBuffer);
if(!receivedMessage.equals("exit")) {
System.out.println("A says: " + receivedMessage);
}
else {
input = "exit";
}