2017-08-25 3 views
1

J'essaye de construire un simple UDPServer et UDPClient. Une comparaison de chaînes ne fonctionne pas.
Voici ce que je suis arrivé à ce jour:Pourquoi ce String.equals() ne fonctionne pas?

import java.io.*; 
import java.net.*; 
import java.util.concurrent.TimeUnit; 

public class UDPSender 
{ 
    public static void main(String args[]) throws Exception 
     { 
     DatagramSocket serverSocket = new DatagramSocket(9877); 
      byte[] receiveData = new byte[1024]; 
      byte[] sendData = new byte[1024]; 
      boolean weiter = true; 

      do { 
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
        serverSocket.receive(receivePacket); 
        String sentence = new String(receivePacket.getData()); 
        System.out.println("RECEIVED: " + sentence); 
        InetAddress IPAddress = receivePacket.getAddress(); 
        int port = receivePacket.getPort(); 

        /*I'm trying to make the if()-statement true, but the program always enters the else()-clause, no matter what I do.*/ 
        if("Shutdown".equals(sentence)) { 
         weiter = false; 
         String bye = ("Auf Wiedersehen! Verbindung wird gekappt..."); 
         sendData = bye.getBytes(); 
         DatagramPacket sendPacket = 
           new DatagramPacket(sendData, sendData.length, IPAddress, port); 
         serverSocket.send(sendPacket); 
         serverSocket.close(); 
        } else {      
         String capitalizedSentence = sentence.toUpperCase(); 
         sendData = capitalizedSentence.getBytes(); 
         DatagramPacket sendPacket = 
           new DatagramPacket(sendData, sendData.length, IPAddress, port); 
         serverSocket.send(sendPacket);      
        } 
       } while(weiter); 
     } 
} 

Et ceci est le client:

import java.io.*; 
import java.net.*; 
import java.util.ArrayList; 

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]; 

     //Look, I'm explicitly sending Shutdown, too!    
     String sentence = "Shutdown"; 
     sendData = sentence.getBytes(); 
     DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877); 
     clientSocket.send(sendPacket); 
     DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
     clientSocket.receive(receivePacket); 
     String modifiedSentence = new String(receivePacket.getData()); 
     System.out.println("FROM SERVER:" + modifiedSentence); 
     clientSocket.close(); 
    } 
} 

Je serais heureux si les deux fonctionnerait sur le même ordinateur pour l'instant, mais après ce problème de chaîne est fixe, j'ai besoin d'avoir plus de PC impliqués. Je ai essayé toutes les solutions proposées dans d'autres questions similaires sur stackoverflow et tout ce que google énumérés sur les trois premières pages, rien n'a fonctionné pour moi. Pouvez-vous voir quelque chose que je ne peux pas?

+1

Avez-vous vérifié t hat 'phrase' n'est pas rempli avec des caractères nulles, des espaces (ou d'autres non-imprimables)? –

+1

Prenez un débogueur, exécutez le code en lui, mettez un point d'arrêt à la comparaison, vérifiez ce qui est exactement dans la variable. –

+0

Mark Rotteveel, votre soupçon s'est avéré être correct. Il y avait des caractères nuls. ^^; La solution de Reimeus l'a fixée pour moi. Merci ^^ – Aye

Répondre

0

Le problème ici est que vous comptez sur le tampon de taille fixe byte[] ... = new byte[1024] pour envoyer et recevoir des paquets.

Mon conseil est d'envoyer uniquement les données que vous avez vraiment besoin:

String sentence = "Shutdown"; 
byte[] sendData = sentence.getBytes(); 
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9877); 

... et créer l'instance String sur le côté serveur en conséquence à la longueur obtenue à partir de la méthode receivePacket.getLength():

String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength()); 

Voir aussi public String(byte[] bytes, int offset, int length)