- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我按照 Android 指南建立了蓝牙连接。
为了分离事物并使它们独立,我决定将 BT 的发送部分放在一个单独的线程中。为了实现这一点,我将 BT-Socket 的“OutStream”传递给一个单独的 Thread 类。我的问题是,一旦我启动这个线程,传入的消息就不再是红色的了。
但我不知道为什么,因为我现在不使用这个线程。它已启动,但未在其中写入任何消息。
这是接收消息的“ConnectedToDevice”类的一部分。我使用一种特殊的方法来检测我的消息是否已完全收到。
public void run() {
byte[] buffer = new byte[1024];
int bytes;
sendPW();
int len = 0;
Communication.getInstance().setFrequentSending(OVS_CONNECTION_IN_PROGRESS);
Communication.getInstance().setSendingMessages(mmOutStream); //Passing the OutStream to the sending class.
Communication.getInstance().setReceivingMessages(queueReceivingMsg);
Communication.getInstance().startThreads(); //currently: only start sending thread.
while (true) {
try {
bytes = this.mmInStream.read(buffer, len, buffer.length - len);
len += bytes;
if (len >= 3 && buffer[2] != -1) {
len = 0;
Log.d(TAG, "run: To Short?");
} else if (len >= 5) {
int dataLength = Integer
.parseInt(String.format("%02X", buffer[3]) + String.format("%02X", buffer[4]), 16);
if (len == 6 + dataLength) {
queueReceivingMsg.add(buffer);
Log.d(TAG, "run: Added to queue");
len = 0;
}
Log.d("BSS", "dataLenght: " + Integer.toString(dataLength) + " len " + len);
}
} catch (IOException var5) {
cancel();
Communication.getInstance().interruptThreads();
return;
}
}
}
发送消息类的重要部分
public static BlockingQueue<Obj_SendingMessage> sendingMessages = new LinkedBlockingQueue<>();
@Override
public void run() {
while (!isInterrupted()) {
if (bGotResponse){
try{
sendingMessage = sendingMessages.take();
send(sendingMessage.getsData());
bGotResponse = false;
lTime = System.currentTimeMillis();
} catch (InterruptedException e){
this.interrupt();
}
}
if((System.currentTimeMillis()%500 == 0) && System.currentTimeMillis() <= lTime+1000){
if(sendingMessage != null){
send(sendingMessage.getsData());
}
} else {
bGotResponse =true;
}
}
}
//Where the outStream is used
private void write(int[] buffer) {
try {
for (int i : buffer) {
this.mmOutputStream.write(buffer[i]);
}
} catch (IOException var3) {
}
}
再次澄清,sendingMessages
始终为空,但消息仍然无法正确接收。
最佳答案
这里提出了从流中读取消息的健壮代码的外观。该代码可以通过以下方式处理部分消息和多条消息:
在编写这段代码时,我注意到代码中的另一个错误。如果找到消息,则不会复制数据。相反,缓冲区被返回。但是,在处理前一条消息之前或处理前一条消息时,缓冲区以及因此返回的消息可能会被下一条消息覆盖。
这个错误比流数据的不良解码更严重。
private byte[] buffer = new byte[1024];
private int numUnprocessedBytes = 0;
public void run() {
...
while (true) {
try {
int numBytesRead = mmInStream.read(buffer, numUnprocessedBytes, buffer.length - numUnprocessedBytes);
numUnprocessedBytes += numBytesRead;
processBytes();
} catch (IOException e) {
...
}
}
}
private void processBytes() {
boolean tryAgain;
do {
tryAgain = processSingleMessage();
} while (tryAgain);
}
private boolean processSingleMessage() {
if (numUnprocessedBytes < 5)
return false; // insufficient data to decode length
if (buffer[2] != (byte)0xff)
// marker byte missing; discard some data
return discardInvalidData();
int messageLength = (buffer[3] & 0xff) * 256 + (buffer[4] & 0xff);
if (messageLength > buffer.length)
// invalid message length; discard some data
return discardInvalidData();
if (messageLength > numUnprocessedBytes)
return false; // incomplete message; wait for more data
// complete message received; copy it and add it to the queue
byte[] message = Arrays.copyOfRange(buffer, 0, messageLength);
queueReceivingMsg.add(message);
// move remaining data to the front of buffer
if (numUnprocessedBytes > messageLength)
System.arraycopy(buffer, messageLength, buffer, 0, numUnprocessedBytes - messageLength);
numUnprocessedBytes -= messageLength;
return numUnprocessedBytes >= 5;
}
private boolean discardInvalidData() {
// find marker byte after index 2
int index = indexOfByte(buffer, (byte)0xff, 3, numUnprocessedBytes);
if (index >= 3) {
// discard some data and move remaining bytes to the front of buffer
System.arraycopy(buffer, index - 2, buffer, 0, numUnprocessedBytes - (index - 2));
numUnprocessedBytes -= index - 2;
} else {
// discard all data
numUnprocessedBytes = 0;
}
return numUnprocessedBytes >= 5;
}
static private int indexOfByte(byte[] array, byte element, int start, int end) {
for (int i = start; i < end; i++)
if (array[i] == element)
return i;
return -1;
}
关于java - 在其他线程中使用蓝牙连接的OutputStream会干扰消息的接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58079336/
例如: 我使用 ObjectInput/OutputStream 通过 Socket outputStream 发送一个 byte[]: ObjectOutputStream myOutput = n
在我看来,ObjectInputStream/ObjectOutputStream和DataInputStream/DataOutputStream都可以应用于实例原始类型。当ObjectInputS
这个问题已经有答案了: Should one call .close() on HttpServletResponse.getOutputStream()/.getWriter()? (6 个回答)
如果我只是在输出流中调用 close(),输出是有保证的,还是需要我总是调用 flush()? 最佳答案 虽然 close 应该调用 flush,但它比这要复杂一些... 首先,装饰器(如 Buffe
我正在通过 USB 连接将数据从我的 Java 应用程序推送到另一端的 Arduino。 Arduino 只能在其末尾缓冲 64 字节的数据,因此我必须限制从我的 Java 应用程序的每个“gulp”
关注 question我之前问过:我正在实现 ByteArrayOutputStream有容量限制。我的主要限制是可用内存量。所以有这样的流os : 当我写的不止是 1MB到我需要“停止”的输出流。
在HttpServlet.doGet(...)中,我使用以下命令从OutputStream中获取HttpServletResponse: resp.getOutputStream(); 写入该输出流时
基本上,我想将控制台输出重定向到 javafx TextArea。我现在正在使用此代码。 public static void init() { //GUI code. TextArea va
我正在尝试从服务器下载文件,服务器向我发送一个没有扩展名的八位字节流,但它在 http header 中发送扩展名(名称为 fileType)。 我想做的是读取该http header ,然后将文件类
我使用一个 API(有关更多信息,请参阅下文),它接受 OutputStream 来捕获数据。相反,我想提供一个 Consumer 的 Strings 来消耗一行又一行的数据。因此我必须编写一个 Ou
我正在处理 Microsoft word 2007 文档。 我的目标是实现: 表格单元格。 段落行。 所以,我的代码可以完成这项工作,但问题是当我使用 FileOutputStream 写入文件时,它
我有一个OutputStream,可以将其初始化为OutputStreams 链。可以有任何级别的链接。唯一可以保证的是链的末尾是一个 FileOutputStream。 我需要使用 FileOutp
我正在为类制作一个简单的 Java 程序,该程序应该将变量 petName、petType 和 numVisits 输出到名为“PatientData.txt”的 txt 文件。我正确打印了 petT
我有以下代码在 Java 程序中将字节数组写入 OutputStream。 public static void write(OutputStream out, ArrayList buffer) t
所以我开始思考这将是一个简单的 1 或 2 行代码,以便我将 OutputStream 转换为字符串,以便我可以用我的逻辑更好地检查它。 所以下面的代码是我目前正在使用的代码。如果我只想将输出写入控制
Java 中的OutputStream 有一个名为flush() 的方法。根据其文档: Flushes this output stream and forces any buffered outpu
好的,我正在实现 NSOutput 和输入流。当它们被初始化时,流打开并连接到我在我的 PC 上运行的 TCPServer,但随后似乎在初始化函数之外关闭一次,或者流可能没有正确存储。我不太确定,所以
这个问题在这里已经有了答案: How do you clear a stringstream variable? (9 个回答) 关闭 9 年前。 目前我正在像这样将一些数据存储到输出流中 std:
我想写入正在运行的进程(不是 Java)的标准输入。如何直接获取 Process 对象或 OutputStream? Runtime.getRuntime() 只能帮助我产生新的东西,而不是找到现有的
将一些处理后的内容写出到输出流后,我需要重新访问流的开头并写出一些内容元数据。我正在写入的数据非常大,多达 4Gb,并且可能会直接写入文件或内存缓冲区,具体取决于各种环境因素。 如何实现一个 Outp
我是一名优秀的程序员,十分优秀!