Skip to content

Instantly share code, notes, and snippets.

@ijokarumawak
Last active June 2, 2016 14:21
Show Gist options
  • Save ijokarumawak/a735546c85244e8386dee288ffa34c44 to your computer and use it in GitHub Desktop.
Save ijokarumawak/a735546c85244e8386dee288ffa34c44 to your computer and use it in GitHub Desktop.
try (
final PipedOutputStream outputStream = new PipedOutputStream();
final PipedInputStream inputStream = new PipedInputStream(outputStream);
final ReadableByteChannel channel = Channels.newChannel(inputStream);
) {
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(300);
outputStream.write(("idx:" + i).getBytes());
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
final ByteBuffer buffer = ByteBuffer.allocate(5);
while ((channel.read(buffer)) > -1) {
buffer.flip();
logger.info("read {}", new String(buffer.array()));
}
}
final PipedOutputStream outputStream = new PipedOutputStream();
final PipedInputStream inputStream = new PipedInputStream(outputStream);
new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1_000);
outputStream.write(i);
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
for (int read; (read = inputStream.read()) > -1;) {
logger.info("read {}", read);
}
public void encode(DataPacket dataPacket, OutputStream encodedOut) throws IOException {
final CountDownLatch dataPacketIsSent = new CountDownLatch(1);
final Thread sendingThread = new Thread(() -> {
try {
super.encode(dataPacket, encodedOut);
dataPacketIsSent.countDown();
} catch (Exception e) {
logger.error("Failed to send packet.", e);
}
});
sendingThread.start();
try {
if (!dataPacketIsSent.await(5, TimeUnit.SECONDS)) {
throw new IOException(new TimeoutException("Sending dataPacket has been timeout."));
}
} catch (InterruptedException e) {
throw new IOException(e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment