问题:Java 读取套接字(蓝牙)输入流,直到读取字符串 ()

发布于 2024-10-04 02:55:04 字数 2305 浏览 5 评论 0 原文

我使用以下代码(来自蓝牙聊天示例应用程序)来读取传入数据并根据读取的字节构造一个字符串。我想一直读到这个字符串到达​​ 。如何使用 read() 函数插入这个条件?

整个字符串看起来像这样 xxxyyy。但 read() 函数不会一次读取整个字符串。当我显示字符时,我看不到同一行中的所有字符。它看起来像:

发件人:

发件人:G>xx

发件人:x

我在手机 (HTC Desire) 上显示字符,并使用 Windows 超级终端发送数据。

如何确保所有字符都显示在一行中?我尝试过使用 StringBuilder 和 StringBuffer 而不是 new 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;
            }
        }
    }

I use the following code (from Bluetooth Chat sample app) to read the incoming data and construct a string out of the bytes read. I want to read until this string has arrived <!MSG>. How to insert this condition with read() function?

The whole string looks like this <MSG><N>xxx<!N><V>yyy<!V><!MSG>. But the read() function does not read entire string at once. When I display the characters, I cannot see all the characters in the same line. It looks like:

Sender: <MS

Sender: G><N>xx

Sender: x<V

.

.

.

I display the characters on my phone (HTC Desire) and I send the data using windows hyperterminal.

How to make sure all the characters are displayed in a single line? I have tried using StringBuilder and StringBuffer instead of new String() but the problem is read() function does not read all the characters sent. The length of the input stream (bytes) is not equal to actual length of the string sent. The construction of string from the read bytes is happening alright.

Thank you for any suggestions and time spent on this. Also please feel free to suggest other mistakes or better way of doing below things, if any.

Cheers,

Madhu

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;
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灰色世界里的红玫瑰 2024-10-11 02:55:04

read 函数对其返回的字节数不做任何保证(它通常会尝试从流中返回尽可能多的字节,而不会阻塞)。因此,您必须缓冲结果,并将它们放在一边,直到获得完整的消息。请注意,您可能会在 "" 消息之后收到某些内容,因此您必须小心不要将其丢弃。

您可以尝试以下方法:

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
    }
}

The read function does not make any guarantee about the number of bytes it returns (it generally tries to return as many bytes from the stream as it can, without blocking). Therefore, you have to buffer the results, and keep them aside until you have your full message. Notice that you could receive something after the "<!MSG>" message, so you have to take care not to throw it away.

You can try something along these lines:

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文