1

This is my first time using a Socket client Server system. I'm running into an error with the server side of my system and I do not know where it is coming from. My client is running fine and closing but my server this is the function for

   public void run() throws Exception
{
      ServerSocket SRVSCK = new ServerSocket(444);
      Socket Sock = SRVSCK.accept();
      String Message="";
      InputStreamReader IR = new InputStreamReader(Sock.getInputStream());
      BufferedReader BR = new BufferedReader(IR);
      Message = BR.readLine();
      while(Message!="exit"){
      System.out.println(Message);
      Message = BR.readLine();
      }
      SRVSCK.close();
      Sock.close();
     System.out.println("here");
   }

But this is the error I'm getting. It doesn't get out the while loop. I've tried breaking out the loop early based on the value of Message but it doesn't. And I can't figure out why. I've checked the thread and nothing seems to be the same. If it matters the information from the client is coming from a file.

3
  • Use the java convention for variables to make the code readable. message, sock should be lowercase Commented May 8, 2015 at 7:47
  • Thanks everyone. I actually am boggled that the solution was so simple and totally unrelated to what I thought it was. Commented May 8, 2015 at 7:53
  • if you are not sure that client sends all command in lowercase, you should use while(!Message.equalsIgnoreCase("exit")) instead. Commented May 8, 2015 at 7:54

2 Answers 2

2

First of all, you should probably stick to Java naming conventions of starting with lowercase for variable names. Next, when comparing Strings, don't use :

string1 == string2
string1 != string2

Those won't work. Instead, use

string1.equals(string2)
Sign up to request clarification or add additional context in comments.

2 Comments

Just to be complete : == and != do not work in this case because they test if the left hand side points to the same memory location as the right hand side. i.e. if they point to the exact same object.
Yep, sorry I forgot to add the more in-depth explanation.
1

Message!="exit" should not be used for string comparison. To compare String in java equals method is used. Use

!Message.equals("exit")

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.