Java Android:从缓冲区读取,直到收到特定的字符或字符串
我对这个网站和android都是新手。我正在尝试为TCP客户端编写代码。我可以发送数据,也可以接收数据。我想从in缓冲区中读取,我可以使用Java Android:从缓冲区读取,直到收到特定的字符或字符串,java,android,Java,Android,我对这个网站和android都是新手。我正在尝试为TCP客户端编写代码。我可以发送数据,也可以接收数据。我想从in缓冲区中读取,我可以使用in.readLine()但这将一直读到新的一行。我会一直读到收到或缓冲区为空或接收到的响应中的数据超过160个字符 我现在的代码是 bSend.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try {
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=新的BufferedReader(新的InputStreamReader(s.getInputStream());;
while(total.length()<160&&total.endsWith(!!”)==false){//如果字符串长度小于160个字符且不以!!
int c=in.read();//读取缓冲区中的下一个字符
if(c==-1)break;//in.read()如果到达缓冲区的末尾,则返回-1
total+=(char)c;//将char添加到字符串
}
in.close();
您可以拆分()
您阅读的行以检查代码>。如果您找到它,响应的最后一部分将在字符串的第一部分,下一条消息(假设有)将在后一部分。@Geobits您的意思是我将使用.readLine
?在这种情况下,如果响应中没有“\n”,我将如何继续?
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();