问题:Java-Read套接字(蓝牙)输入流直到读取字符串(<!MSG>)

Mad*_*dan 1 java stringbuilder conditional inputstream

我使用以下代码(来自蓝牙聊天示例应用程序)来读取传入的数据并从读取的字节中构造一个字符串.我想阅读,直到这个字符串到达<!MSG>.如何使用read()函数插入此条件?

整个字符串看起来像这样<MSG><N>xxx<!N><V>yyy<!V><!MSG>.但read()函数不会立即读取整个字符串.当我显示字符时,我看不到同一行中的所有字符.看起来像:

发件人: <MS

发件人: G><N>xx

发件人: x<V

.

.

.

我在手机上显示字符(HTC Desire),然后使用windows hyperterminal发送数据.

如何确保所有字符都显示在一行?我曾尝试使用StringBuilder和StringBuffer而不是新的String()但问题是read()函数没有读取所有发送的字符.输入流的长度(字节)不等于发送的字符串的实际长度.从读取字节构造字符串正好发生.

感谢您对此提出的任何建议和时间.另外,如果有的话,请随时提出其他错误或更好的做法.

干杯,

马杜

public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        //Writer writer = new StringWriter();
        byte[] buffer = new byte[1024];           
        int bytes;
        //String end = "<!MSG>";
        //byte compare = new Byte(Byte.parseByte(end));

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                //boolean result = buffer.equals(compare);
                //while(true)   {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    //Reader reader = new BufferedReader(new InputStreamReader(mmInStream, "UTF-8"));
                    //int n;
                    //while ((bytes = reader.read(buffer)) != -1)   {   
                        //writer.write(buffer, 0, bytes);

                    //StringBuffer sb = new StringBuffer();                    
                    //sb = sb.append(buffer);

                    //String readMsg = writer.toString();
                    String readMsg = new String(buffer, 0, bytes);

                    //if (readMsg.endsWith(end))
                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, readMsg)
                            .sendToTarget();                        
                //}                    

            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Fla*_*vio 5

read函数不保证它返回的字节数(它通常会尝试从流中返回尽可能多的字节,而不会阻塞).因此,您必须缓冲结果,并将它们放在一边,直到您收到完整的消息.请注意,您可以在"<!MSG>"邮件后收到一些内容,因此您必须注意不要丢弃它.

你可以尝试这些方面:

byte[] buffer = new byte[1024];
int bytes;
String end = "<!MSG>";
StringBuilder curMsg = new StringBuilder();

while (-1 != (bytes = mmInStream.read(buffer))) {
    curMsg.append(new String(buffer, 0, bytes, Charset.forName("UTF-8")));
    int endIdx = curMsg.indexOf(end);
    if (endIdx != -1) {
        String fullMessage = curMsg.substring(0, endIdx + end.length());
        curMsg.delete(0, endIdx + end.length());
        // Now send fullMessage
    }
}
Run Code Online (Sandbox Code Playgroud)