Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
#66)

* implement workaround for marianobarrios/tls-channel#233

* add comments

* clarify exception messages
  • Loading branch information
kortemik authored May 28, 2024
1 parent e3f7c69 commit 28c246f
Showing 1 changed file with 34 additions and 20 deletions.
54 changes: 34 additions & 20 deletions src/main/java/com/teragrep/rlp_01/RelpClientTlsSocket.java
Original file line number Diff line number Diff line change
Expand Up @@ -182,31 +182,45 @@ void close() throws IOException {

@Override
int read(ByteBuffer byteBuffer) throws IOException, TimeoutException {
int readBytes = -1;
int readBytes;
try {
// try reading data if it is available from the tlsChannel
readBytes = tlsChannel.read(byteBuffer);
}
catch (NeedsReadException | NeedsWriteException e) {
// there is no more data, zero read will need selector to work on it
readBytes = 0;
}

SelectionKey key = this.socketChannel.register(this.selector, SelectionKey.OP_READ);
int nReady = selector.select(this.readTimeout);
if (nReady == 0) {
throw new TimeoutException("read timed out");
if (readBytes == -1) {
throw new IOException("Read failed, end-of-stream reached");
}
Set<SelectionKey> polledEvents = this.selector.selectedKeys();
Iterator<SelectionKey> eventIter = polledEvents.iterator();
while (eventIter.hasNext()) {
SelectionKey currentKey = eventIter.next();
// tlsChannel needs to know about both
if (currentKey.isReadable() || currentKey.isWritable()) {
try {
readBytes = tlsChannel.read(byteBuffer);
if (readBytes == -1) {
throw new IOException("read failed");

if (readBytes == 0) {
SelectionKey key = this.socketChannel.register(this.selector, SelectionKey.OP_READ);
int nReady = selector.select(this.readTimeout);
if (nReady == 0) {
throw new TimeoutException("Read timed out");
}
Set<SelectionKey> polledEvents = this.selector.selectedKeys();
Iterator<SelectionKey> eventIter = polledEvents.iterator();
while (eventIter.hasNext()) {
SelectionKey currentKey = eventIter.next();
// tlsChannel needs to know about both
if (currentKey.isReadable() || currentKey.isWritable()) {
try {
readBytes = tlsChannel.read(byteBuffer);
if (readBytes == -1) {
throw new IOException("Read failed, end-of-stream reached");
}
} catch (NeedsReadException e) {
key.interestOps(SelectionKey.OP_READ); // overwrites previous value
} catch (NeedsWriteException e) {
key.interestOps(SelectionKey.OP_WRITE); // overwrites previous value
}
} catch (NeedsReadException e) {
key.interestOps(SelectionKey.OP_READ); // overwrites previous value
} catch (NeedsWriteException e) {
key.interestOps(SelectionKey.OP_WRITE); // overwrites previous value
}
eventIter.remove();
}
eventIter.remove();
}
return readBytes;
}
Expand Down

0 comments on commit 28c246f

Please sign in to comment.