如何从android中的socket读取数据

时间:2014-04-07 11:52:09

标签: android sockets

我想用RN171连接我的Android应用程序。

这是我的代码:

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

我正在向RN171发送get everything命令,并希望提醒其输出。

但是应用程序会运行一段时间,并且消息显示应用程序没有响应。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

您在读取输入直到流结束,并且在您获得之前没有做任何事情。除非设备断开连接,否则您将永远阻止。您需要处理每个数据。