2011-12-29 10 views
1

このアプリケーションでは、ユーザーからコマンドが送信され、サーバーから返信が返されます。何らかの理由でifステートメントが機能しておらず、入力ごとにsentance = "Unknown Command" + '\n';が実行されます。私は何が間違っているのだろうと思っていた。Java TCP ifステートメント

import java.io.*; 
import java.net.*; 

// SERVER 

class StartingPoint { 
    public static void main(String argv[]) throws Exception{ 

     double srvversion = 0.1; 
     double cliversion = 0.1; 

     String clientSentence; 
     String sentance = null; 
     String capitalizedSentence; 

     //Commands cmds = new Commands(); 

     ServerSocket welcomeSocket = new ServerSocket(6789); 
     System.out.println("Server Started"); 
     while (true) { 

      Socket connectionSocket = welcomeSocket.accept(); 
      BufferedReader inFromClient = new BufferedReader(
        new InputStreamReader(connectionSocket.getInputStream())); 
      DataOutputStream outToClient = new DataOutputStream(
        connectionSocket.getOutputStream()); 
      clientSentence = inFromClient.readLine(); 
      System.out.println("Received: " + clientSentence); 
      capitalizedSentence = clientSentence.toUpperCase(); 


      if(capitalizedSentence == "VERSION"){ 
       sentance = "Current Server Version: " + srvversion 
         + " | Current Client Version: " + cliversion + '\n'; 
      }else{ 
       sentance = "Unknown Command" + '\n'; 
      } 

      outToClient.writeBytes(sentance); 
      System.out.println("Sent: " + sentance); 
     } 
    } 
     } 
+0

あなたは、おそらくどのような無効なコマンド_was_をプリントアウトする必要があります - - 少なくともこれをデバッグしようとしている間に.... – sarnold

答えて

2

==を使用する代わりに文字列を比較するには、.equals()メソッドを使用する必要があります。

if(capitalizedSentence.equals("VERSION")){ 
+0

そのための歓声 – Sock

1

に変更

if(capitalizedSentence == "VERSION"){ 

文字列を比較するには、次のよう.equals()メソッドを使用する必要があります。

String str1; 
String str2; 

if (str1.equals(str2)) // do something 
else //do something else