SzeKaKa
SzeKaKa

Reputation: 41

Cannot read data from ServerSocket in Java

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

Upvotes: 0

Views: 48

Answers (2)

Sanjeev
Sanjeev

Reputation: 9946

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.

Upvotes: 2

Vimal Bera
Vimal Bera

Reputation: 10497

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.

Upvotes: 1

Related Questions