这是我正在谈论的简单UDP server。
我们如何检查通过客户端发送的字符串是否与收到的字符串相同?我尝试了一个简单的if条件来检查它们是否相等,使用了字符串的equal()方法,但即使消息是相同的,if条件结果为false,即使使用.toString()比较发送和接收的消息方法。
import java.net.*;
import java.io.*;
import java.util.Arrays;
public class UDPClient {
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 7777);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String sentSentence = new String(sendPacket.getData());
String receivedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + receivedSentence + "\n" + "IP Address: " + receivePacket.getAddress() + "\n" +
"Message Size: " + receivePacket.getData().length);
clientSocket.close();
System.out.println(sentSentence + " " + receivedSentence);
if(sentSentence.equals(receivedSentence.toString()))
System.out.println("OK" + " " + sentence + " " + receivedSentence);
else
System.out.println("FAILED");
}
}
答案 0 :(得分:1)
String sentSentence = new String(sendPacket.getData());
String receivedSentence = new String(receivePacket.getData());
正如预期的那样,您无法正确构建这些Strings
。它应该是:
String sentSentence = new String(sendPacket.getData(), sendPacket.getOffset(), sendPacket.getLength());
String receivedSentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());