0

The code below is in server side. It could handle client request and then show the client input in my console.

Yet, the problem appears...

The console shows the string "hello from clientA" successfully. But, I cannot use "if" to analyze this word.

My objective is to show "ok" in console if it is a request from "clientA". To conclude that, the program does not reach "System.out.println("ok")" even though it matches the condition.

Please help me )...(

Thanks.

while(true)
  {
     Socket server = null;
     try
     {
        server = serverSocket.accept();
        DataInputStream in =
           new DataInputStream(server.getInputStream());
        obtain=in.readUTF();

        DataOutputStream out =
             new DataOutputStream(server.getOutputStream());
        out.writeUTF("server say hello to you");

        System.out.println(obtain);//the console show "hello from clientA" exactly
        if(obtain=="hello from clientA")
        {
            System.out.println("ok");
        }
        server.close();
     }catch(SocketTimeoutException s)
     {
         System.out.println("Again");
         try {
            serverSocket.setSoTimeout(20000);
        } catch (IOException e) {
        }
     }
     catch(Exception b)
     {
         break;
     }
  }
1

2 Answers 2

2

Do not use == to compare strings, use String#equals() method so

if(obtain=="hello from clientA")

should be replaced by

if("hello from clientA".equals(obtain))

hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to your answer. I have never faced this problem before. Your fast reply solved the problem, where I wasted 6 hours. Thanks so much.
Glad it helped you. Have fun coding :)
1

Change that if condition to this :

if(obtain.equals("hello from clientA"))
    {
        System.out.println("ok");
    }

== operator is checking the reference of the value and not the actual value. Whereas String#equals compare the value of object and return TRUE or FALSE accordingly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.