From df4a8b7cb85d0576065be04f2cd61f4a47c0b7a3 Mon Sep 17 00:00:00 2001 From: Kevin Herron Date: Sun, 30 Apr 2017 06:48:46 -0700 Subject: [PATCH] Block/loop until all bytes are written SerialOutputStream Ensures that the write methods of SerialOutputStream fulfill their contract by acknowledging the possibility that not all bytes could be written in the first call to native writeBytes() and looping until all bytes have been written. --- .../com/fazecast/jSerialComm/SerialPort.java | 45 +++++++++++++++---- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/fazecast/jSerialComm/SerialPort.java b/src/main/java/com/fazecast/jSerialComm/SerialPort.java index c80dcc8..2ec0155 100644 --- a/src/main/java/com/fazecast/jSerialComm/SerialPort.java +++ b/src/main/java/com/fazecast/jSerialComm/SerialPort.java @@ -1107,23 +1107,50 @@ public final class SerialPort @Override public final void write(int b) throws IOException { - if (!isOpened) - throw new IOException("This port appears to have been shutdown or disconnected."); + int bytesWritten = 0; - singleByteBuffer[0] = (byte) (b & 0xFF); + do { + if (!isOpened) + throw new IOException("This port appears to have been shutdown or disconnected."); - if (writeBytes(portHandle, singleByteBuffer, 1L) < 0) - throw new IOException("This port appears to have been shutdown or disconnected."); + singleByteBuffer[0] = (byte) (b & 0xFF); + + bytesWritten += writeBytes(portHandle, singleByteBuffer, 1L); + + if (bytesWritten < 0) + throw new IOException("This port appears to have been shutdown or disconnected."); + + if (bytesWritten == 0) sleep1(); + } while (bytesWritten < 1); } @Override public final void write(byte[] b) throws IOException { - if (!isOpened) - throw new IOException("This port appears to have been shutdown or disconnected."); + int bytesWritten = 0; + byte[] buffer = b; - if (writeBytes(portHandle, b, b.length) < 0) - throw new IOException("This port appears to have been shutdown or disconnected."); + do { + if (!isOpened) + throw new IOException("This port appears to have been shutdown or disconnected."); + + int written = writeBytes(portHandle, buffer, 1L); + + if (written < 0) + throw new IOException("This port appears to have been shutdown or disconnected."); + + bytesWritten += written; + + if (written == 0) + { + sleep1(); + } + else + { + buffer = new byte[b.length - bytesWritten]; + System.arraycopy(b, bytesWritten, buffer, 0, buffer.length); + } + } while (bytesWritten < b.length); } @Override