Android Socket读取问题

时间:2017-02-26 04:34:24

标签: java android sockets

我创建了一个连接到Raspberry pi热点的套接字。我能够成功连接到它并发送一个字符串到pi。但是,由于我尝试实现读取功能以从pi获取数据,因此我遇到了一些问题。

每次我运行while循环或只是有一个" response = myBufRead.readLine()"时,程序会停止。

private class StatusCheck extends AsyncTask<Void, Void, Void> {


    @Override
    protected Void doInBackground(Void... params) {
        //debug vibrations and text
        if(vibrate) {
            Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            vib.vibrate(100);
        }
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            Log.d(debugStr, "In initial connect");
            mySocket = new Socket(serverAddr, SERVERPORT);

        } catch (UnknownHostException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if (mySocket == null) {
                str1 = "Socket became null";
                return null;
            }
            str1 = "Connected";
            try {
                PrintWriter myPrintWriter = new PrintWriter(mySocket.getOutputStream(), true);
                InputStreamReader myInputStreamRead = new InputStreamReader(mySocket.getInputStream());
                BufferedReader myBufRead = new BufferedReader(myInputStreamRead);
                Log.d(debugStr, "In out created");

                myPrintWriter.write(recordName);

                Log.d(debugStr, String.valueOf(myBufRead.ready()));
                Log.d(debugStr, "About to enter while loop");
                while((response = myBufRead.readLine()) != null) {
                    Log.d(debugStr, "in while loop");
                    response = myBufRead.readLine();
                    Log.d(debugStr, String.valueOf(myBufRead.ready()));
                    Log.d(debugStr, myBufRead.readLine());
                    Log.d(debugStr, String.valueOf(myBufRead.ready()));
                }
                Log.d(debugStr, "out of while loop");
                myPrintWriter.close();
                myInputStreamRead.close();
                myBufRead.close();


            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                mySocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return null;
        }

    }


}

任何人都知道为什么会这样吗?感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

BuffereadReader.readLine()是一种阻塞方法,所以它会等待,并且正如你所说的那样,“停止”它的线程,直到它有东西要读。您是否在从pi发送流后调用flush()

另一个问题可能是readLine()将等待一个完整的行,即它会等到它读取行分隔符。您是否从pi发送了行分隔符?见Socket Multithreading - Reading input stream pauses thread

你可以这样做(假设你正在使用BufferedWriter来自pi端):

bufferedWriter.write(text);
bufferedWriter.newLine();
bufferedWriter.flush();