所以我被要求创建一个UDP消息传递应用程序。我有两个客户端在同一台计算机上从命令行运行,我试图让每个客户端在从另一个客户端收到字符串"exit"
时突破while循环,因此它们都终止同时进行。
String input
,因此如果此客户端输入"exit"
,则跳过while(这很好用!)。
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";
}
}
我遇到的问题是我无法将!receivedMessage.equals("exit")
等同于false
,即使我执行System.out.println(receivedMessage)
时,我也会"exit"
。它们看起来完全一样,但显然不是。
我试过强制编码,比如......
String receivedMessage = new String(receiveBuffer, "UTF-8");
......但没有任何作用。我尝试了许多强制编码的其他组合,并将receivedMessage
转换为Byte数组,char数组等进行比较,并且我已检查receivedMessage
两侧的空格,仍然没有。
任何帮助将不胜感激。它必须是我想念的小东西。 感谢。
答案 0 :(得分:0)
也许在receivedMessage中有一些前导或尾随空格。试着修剪它。
答案 1 :(得分:0)
receiveBuffer 大小可能存在问题。目前,您正在数据包中发送“退出”,该数据包足够小,可以容纳 65508 字节。因此, receiveBuffer 中的剩余字节只是空的或包含特殊字符。这就是为什么当您收到数据包并将数据转换为字符串时,字符串中的剩余字节也存在。
您可以使用contains()
代替equals()
来比较字符串,也可以只将包含实际消息的所需字节放入receiveBuffer。以下是实现这一目标的可能方法之一:
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";
}
答案 2 :(得分:0)
receiveSocket.receive(packetToReceive);
receiveBuffer = packetToReceive.getData();
String receivedMessage = new String(receiveBuffer);
问题出在这里。你忽略了收到的数据包的长度。最后两行可以改为:
String receivedMessage = new String(packetToReceive.getData(), packetToReceive.getOffset(), packetToReceive.getLength());