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.