0

我是这个网站的新手,也是安卓的新手。我试图为 TCP 客户端编写代码。我也可以发送数据和接收数据。我想从缓冲区中读取,我可以使用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{

            }
        }


    });
4

1 回答 1

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();
于 2013-10-22T14:32:45.300 回答