@Override
  public AsyncIOWriter write(byte[] data, int offset, int length) throws IOException {

    if (channel.isOpen()) {
      pendingWrite.incrementAndGet();
      final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();

      ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);

      if (headerWritten) {
        c.write(Integer.toHexString(length - offset).getBytes("UTF-8"));
        c.write(CHUNK_DELIMITER);
      }

      c.write(data, offset, length);
      if (headerWritten) {
        c.write(CHUNK_DELIMITER);
      }

      channel.write(c.buffer()).addListener(listener);
      byteWritten = true;
      lastWrite = System.currentTimeMillis();
    } else {
      logger.warn("Trying to write on a closed channel {}", channel);
    }
    headerWritten = true;
    return this;
  }
 void _close() {
   if (!isClosed.getAndSet(true)) {
     headerWritten = false;
     final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
     ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);
     try {
       c.write(ENDCHUNK);
       channel.write(buffer).addListener(ChannelFutureListener.CLOSE);
     } catch (IOException e) {
       logger.trace("Close error", e);
     }
   }
 }
Example #3
0
  /**
   * write a TaskMessage into a stream
   *
   * <p>Each TaskMessage is encoded as: task ... short(2) len ... int(4) payload ... byte[] *
   */
  private void writeTaskMessage(ChannelBufferOutputStream bout, TaskMessage message)
      throws Exception {
    int payload_len = 0;
    if (message.message() != null) payload_len = message.message().length;

    int task_id = message.task();
    if (task_id > Short.MAX_VALUE)
      throw new RuntimeException("Task ID should not exceed " + Short.MAX_VALUE);

    bout.writeShort((short) task_id);
    bout.writeInt(payload_len);
    if (payload_len > 0) bout.write(message.message());
  }