我正在尝试将byte[]
发送到串行端口。然而,outputstream.write(byte[]);
仅在byte[].length
包含少于大约100个字节时才有效。
只是想知道:
byte[]
永远不会包含超过 476 个字节此代码有效:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
for(int i = 0; i<bytes.length; i++){
if(i%10==0){
Thread.sleep(1);
}
outputStream.write(bytes[i]);
}
outputStream.flush();
outputStream.close();
port.disconnect();
优点:适用于所有系统
缺点:可能会不必要地 sleep
这也是:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
for(byte b : bytes){
outputStream.write(b);
}
outputStream.flush();
outputStream.close();
port.disconnect();
优点:无需不必要的 sleep
缺点:可能不适用于快速系统,因为它们可以更快地处理每个
但是如果 bytes 包含的字节数超过大约 100 个字节,下面的代码将会失败:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE);
port.connect();
OutputStream outputStream = port.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
port.disconnect();
虽然write(byte[])
是sun库中的有效方法
我对此有一些想法:
- 我溢出了输出缓冲区,波特率太低,无法立即发送此数据
write(byte[])
不会将byte[]
切成更小的片段
您可能想知道如果我有一个可行的解决方案,为什么我会问这个问题。嗯:
我想知道我的哪一个解决方案更好和/或是否有其他/更好的方法来做到这一点。另外,如果方法的处理能力依赖于硬件(至少在 JavaDoc 中这么说?),为什么要创建一个方法 write(byte[])
呢?
最佳答案
假设我在 google 上搜索了正确的代码,这看起来不像是 Java 的问题,而是 NRSerialPort
库的实现问题。
深入研究代码,我可以看到 SerialOutputStream提供 OutputStream
的实现,并根据 write(byte)
或 write(byte[])
方法调用两种不同的方法使用:
参见here
protected native void writeByte( int b, boolean i ) throws IOException;
protected native void writeArray( byte b[], int off, int len, boolean i )
throws IOException;
如果不深入研究 native 代码,我猜测 writeArray
方法的实现中可能存在错误。
关于java - outputStream.write 有缓冲区溢出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8079836/