Android:从缓冲区读取,直到收到特定的字符或字符串

时间:2013-10-22 14:07:47

标签: java android

我是这个网站以及android的新手。我试图编写TCP客户端代码。我也可以发送数据和接收。我想从in缓冲区中读取,我可以使用in.readLine();,但这只会读到新行。我将阅读,直到收到!!或缓冲区为空或收到的响应中的数据超过160个字符。

我目前的代码是

bSend.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            try {
                String outMsg = textField.getText().toString().trim();
                out.write(outMsg);
                out.flush();
                StringBuilder total = new StringBuilder();
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                mstr=in.readLine();
                tv.setText(mstr);
                Log.i("TcpClient", "sent: " + mstr);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            finally{

            }
        }


    });

1 个答案:

答案 0 :(得分:2)

您可以使用.read()代替.readLine()。

String total = "";
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));;
while (total.length() < 160 && total.endsWith("!!") == false){ // if the string is less then 160 chars long and not ending with !!
    int c = in.read(); // read next char in buffer
    if(c == -1) break; // in.read() return -1 if the end of the buffer was reached
    total += (char)c; // add char to string
}
in.close();