gpt4 book ai didi

java - 安卓 : read from a buffer until a specific char or string is recieved

转载 作者:行者123 更新时间:2023-12-02 06:37:04 24 4
gpt4 key购买 nike

我是这个网站的新手,也是 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{

}
}


});

最佳答案

您可以使用 .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();

关于java - 安卓 : read from a buffer until a specific char or string is recieved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19520206/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com