Mohamed Gamal
Mohamed Gamal

Reputation: 1348

Android Socket in.ReadLine()

My client sends to the client and reads acknowledged successfully from server just for the first time . As i hit send button again it Writes to server but fails to read again.

Heres my code:

Note: doit variables indicates that button pressed then it goes back to 0 till the user hit the button again.

 while (connected) {
                try {
                    Log.d("ClientActivity", "C: Sending command.");

                   b.setOnClickListener(new View.OnClickListener() {

                       public void onClick(View v) {
                           // TODO Auto-generated method stub

                         doit=1;
                         Log.e("ErrorButton","NextTime "+doit);
                       }
                   });  
                  if(doit==1)
                  {
                      Log.e("ErrorButton","If");
                  ////
                      out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                

                    out.println("Helloo");

                    while ((text = in.readLine()) != null) {
                        finall += text;
                        Log.e("Test","Final: "+finall);
                      if(text=="quit")
                      {
                          socket.close();
                      }
                  Log.e("ClientActivity", "After Read "+doit+" "+finall);
                 // in.close();

                   doit=0;
                   Log.e("ClientActivity", "After If "+doit);
                  } 

                  }     



                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }

            } 

Upvotes: 0

Views: 2417

Answers (2)

user207421
user207421

Reputation: 310874

Don't create new streams every time around the loop. create them once for the life of the socket. You are losing buffered data in the streams you are discarding by creating new ones.

Upvotes: 1

user370305
user370305

Reputation: 109237

Because, I think your Socket is not closed,

Look at your code line, your if condition is wrong,

if(text=="quit")

it should be,

if(text.equals("quit"))

To compare a String always use either .equals() or equlaIgnoreCase() method from Java String Class.

Also move out the Button's onClickListener() from the while() loop.

Every-time its create a New Listener Object for Button for each iteration which cause the problem.

Write

b.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
    doit=1;
    Log.e("ErrorButton","NextTime "+doit);
  }
}); 

in onCreate() of Activity.

Upvotes: 1

Related Questions