简体   繁体   English

如何从android中的socket读取数据

[英]how to read data from socket in android

I want to Connect my android application with RN171. 我想用RN171连接我的Android应用程序。

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. 我正在向RN171发送get everything命令并想要提示其输出。

But app runs for sometime and message appears that app is not responding. 但应用程序运行一段时间后,消息显示应用程序没有响应。

How can i do this ? 我怎样才能做到这一点 ?

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. 您需要在获得数据时处理每个数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM