Manoj
Manoj

Reputation: 497

how to read data from socket in android

I want to Connect my android application with RN171.

Here is my code:

try{


InetAddress modemAddr = InetAddress.getByName("1.2.3.4");
        Socket socket = new Socket(modemAddr, 2000);
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
        out.println("$$$");
        out.println("get everything");
        socket.close();
        InetAddress modemAddr2 = InetAddress.getByName("1.2.3.4");
        Socket socket2 = new Socket(modemAddr2, 2000);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket2.getInputStream()));
        String inMsg = "";
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            total.append(line);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
         builder.setTitle("Response");// Set the Title of Alert Dialog
         builder.setMessage(total.toString())
         .setPositiveButton("OK",dialogClickListener).show();
        }
 socket2.close();

}
catch(Exception e)
{
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setTitle("Response");// Set the Title of Alert Dialog
                 builder.setMessage(e.toString())
                 .setPositiveButton("OK",dialogClickListener).show();
}

I am sending get everything command to RN171 and want to alert its output.

But app runs for sometime and message appears that app is not responding.

How can i do this ?

Upvotes: 0

Views: 266

Answers (1)

user207421
user207421

Reputation: 310979

You're reading the input until end of stream, and not doing anything until you get it. Unless the device disconnects, you will therefore block forever. You need to process each piece of data as you get it.

Upvotes: 2

Related Questions