Android Socket继续读取,直到特定的字符串序列

时间:2016-02-23 12:43:43

标签: java android sockets bufferedreader

我想从套接字读取直到特定的字符串序列,如<END>。问题是服务器有时会以块的形式返回数据,即文本(JSON)太长而无法在数据包中发送。我想创建一个逻辑,其中套接字继续附加一个字符串生成器,直到流结束于<END>,之后继续附加另一条消息。

InputStreamReader inr = new InputStreamReader(socket.getInputStream());

BufferedReader br = new BufferedReader(inr);

byte[] resultBuff = new byte[0];
byte[] buff = new byte[99999];
int k;

StringBuilder sb = new StringBuilder();

while ((k = in .read(buff, 0, buff.length)) > -1) {
 byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
 System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
 System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy current lot
 resultBuff = tbuff; // call the temp buffer as your result buff
 System.out.println(resultBuff.length + " bytes read.");
 String s = new String(resultBuff);


 sb.append(s);

 if (s.endsWith(DELIMITER)) {

  String response = sb.toString().replace(DELIMITER, "").replace("\n", "").replace("\r", "");

  System.out.println(response);

  if (listener != null) {
   listener.onMessageReceived(params[0], response);

  } else {
   Log.e(TAG, "Response :: listener.onMessageReceived null ");
  }
  resultBuff = new byte[0];
  sb = new StringBuilder();
 } else {
  sb.append(s);

 }


}

这里的目标是保持while循环运行,以便套接字可以在流中出现任何内容时继续读取。

1 个答案:

答案 0 :(得分:0)

你可以这样做。

String str = "";
byte[] b = new byte[1024];
for(int r = 0; (r = is.read(b))!=-1;){
    str += new String(b,0,r);
    if(str.contains(DELIMITER)){
        String message = str.substring(0,str.indexOf(DELIMITER));
        str = str.substring(str.indexOf(DELIMITER)+DELIMITER.length());
        //process message.
    }
}
if(!str.isEmpty()){
    //the JSON object was sent in a single chunk, porcess it
}

这样做的目的是将从InputStream读取的所有数据存储到str String中,当str包含DELIMITER时,它会提取来自str的消息,以便进行处理。如果缓冲区包含多条消息,则此操作将失败。您可以使用String[] messages = str.split(DELIMITER)来处理该问题。

更好的解决方案是使用Scanner,这是一个例子:

Scanner sc = new Scanner(in);
sc.useDelimiter(DELIMITER);
while(sc.hasNext()){
    String message = sc.next();
    // process message.
}