Search code examples
androidsocketstcpclient

BufferedReader.readline() works only once


I am trying to create an android application which behaves like a client, the problem I am facing is, while receiving string data from the server, app receives it only for the first time. And app receives data again when I reconnect the socket.

I am using socket protocol app as server, I am sending a new line character at the end of the message, and even the connection is alive as I can send data back to the server.

Here's the code

public class MainActivity extends AppCompatActivity {

Thread m_thread;
Socket clientSocket;
PrintWriter out;
boolean fan=false,socket=false,light1=false,light2=false,m_run=false;
int quantity = 0;
String msg;
BufferedReader in = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void Start(View view) {
    m_thread = new Thread(new Runnable() {
        @Override
        public void run() {
            m_run = true;
            try {
                clientSocket = new Socket("192.168.1.34", 2001);
                try {
                    out = new PrintWriter(new BufferedWriter(new       OutputStreamWriter(clientSocket.getOutputStream())));
                    out.println("Client Connected");
                    out.flush();
                    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                    TextView srv_message = (TextView) findViewById(R.id.messageTextView);
                    while(m_run)
                    {
                        if(msg!=null)
                        {

                            srv_message.setText(""+msg);
                        }
                        msg = null;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    m_thread.start();
}

Start method is called when I click the create connection button.


Solution

  • Use this code, it also works for me.

    input =  new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    while (!Thread.currentThread().isInterrupted())
    {
                try
                {
                    read = input.readLine();
                    if (read != null) {
                        // take a handler to Toast the message
                    }
                } 
               catch (Exception e) 
               {
                    e.printStackTrace();
               }
    }