public void sendBinary(final FileChannel payloadChannel, final int offset, final long length, final SendCallback callback) {
try{
if (length > payloadChannel.size() - offset) {
throw WebSocketMessages.MESSAGES.lengthBiggerThenFileChannel();
}
StreamSinkChannel sink = StreamSinkChannelUtils.applyAsyncSendTimeout(session, createSink(length));
long written = 0;
while (written < length) {
long w = sink.transferFrom(payloadChannel, offset + written, length - written);
if (w == 0) {
final long writtenBytes = written;
sink.getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
long written = writtenBytes;
@Override
public void handleEvent(StreamSinkChannel sink) {
try {
while (written < length) {
long w = sink.transferFrom(payloadChannel, offset + written, length - written);
if (w == 0) {
sink.resumeWrites();
return;
}
if (w > 0) {
written += w;
}
}
StreamSinkChannelUtils.shutdownAndFlush(sink, callback);
} catch (IOException e) {
StreamSinkChannelUtils.safeNotify(callback, e);
}
}
});
sink.resumeWrites();
return;
}
if (w > 0) {
written += w;
}