I'm trying to send a byte[]
to a serial port. However outputstream.write(byte[]);
only works when byte[].length
contains less then about 100 bytes.
Just to know:
byte[]
never contains more then 476 bytes This code works:
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();
Advantage: works on all systems
Disadvantage: may sleep unnecessarily
And so does this:
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();
Advantage: no unnecessarily sleeping
Disadvantage: may not work on fast systems because they can process the for each much faster
But the code below will fail if bytes contains more then about 100 bytes:
NRSerialPort port = new NRSerialPort(portname, DEFAULTBAUDRATE); port.connect(); OutputStream outputStream = port.getOutputStream(); outputStream.write(bytes); outputStream.flush(); outputStream.close(); port.disconnect();
Although write(byte[])
is a valid method in the sun library
I have some ideas about this:
write(byte[])
does not cut the byte[]
to smaller pieces You might wonder why I ask this question if I got a working solution. Well:
I want to know which one of my solutions is better and/or if there is a other/better way to do this. besides why make a method write(byte[])
if its processing capability's depend on hardware (at least say so in the JavaDoc?)
Assuming I've googled the correct code, this does not look like a problem with Java but with the implementation of the NRSerialPort
library.
Diving into the code, I can see that SerialOutputStream provides the implementation of the OutputStream
and it calls two different methods depending on whether the write(byte)
or write(byte[])
method is used:
see 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;
Without digging into the native code, I would surmise that there may be a bug in the implementation of the writeArray
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.