简体   繁体   中英

How to check if the sent message is the same as the received message in a simple UDP server

Here's the simple UDP server I'm talking about.

How can we check if the string we send through the client is the same as the one received? I have tried a simple if condition to check if they are equal, using the equal() method of strings but even though the messages are the same the if condition results false, even when comparing the sent and received messages using the .toString() method.

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");

   }
}
String sentSentence = new String(sendPacket.getData());
String receivedSentence = new String(receivePacket.getData());

As expected, you aren't constructing these Strings correctly. It should be:

String sentSentence = new String(sendPacket.getData(), sendPacket.getOffset(), sendPacket.getLength());
String receivedSentence = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM