Exemplo n.º 1
0
  private void handleWritableChannel(SelectionKey key, SelectableChannel channel) {
    try {
      if (!key.isWritable()) return;

      ByteBuffer buffer = this.outputBuffers.get(channel);
      buffer.flip();
      ((WritableByteChannel) channel).write(buffer);

      // If there aren't any bytes left to write from the buffer, tell the
      // selector that we no longer want to write to the channel (and-not
      // disables only that bit)
      if (0 == buffer.remaining()) key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
      buffer.compact();

      // The code below the catch blocks below is for error-handling only
      return;
    } catch (CancelledKeyException e) {
      // Error-handling code below to avoid code duplication
    } catch (ClosedChannelException e) {
      // Error-handling code below to avoid code duplication
    } catch (EOFException e) {
      // Error-handling code below to avoid code duplication
    } catch (IOException e) {
      reportIOException(e);

      // Continue with the error-handling code below
    }

    this.outputBuffers.remove(channel);

    // Close and remove any routes that point to this channel as an output
    Iterator<Map.Entry<SelectableChannel, SelectableChannel>> i =
        this.outputs.entrySet().iterator();
    while (i.hasNext()) {
      Map.Entry<SelectableChannel, SelectableChannel> entry = i.next();
      if (entry.getValue().equals(channel)) {
        closeChannelAndReportException(entry.getKey());
        i.remove();
      }
    }

    try {
      // No longer interested in handling this channel for write
      // operations
      key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    } catch (CancelledKeyException e) {
      // Do nothing
    }

    // The channel should already be closed, but just in case
    closeChannelAndReportException(channel);
  }
Exemplo n.º 2
0
  public static void main(String[] args) throws IOException {

    FileInputStream fin = new FileInputStream(args[0]);
    GZIPInputStream gzin = new GZIPInputStream(fin);
    ReadableByteChannel in = Channels.newChannel(gzin);

    WritableByteChannel out = Channels.newChannel(System.out);
    ByteBuffer buffer = ByteBuffer.allocate(65536);
    while (in.read(buffer) != -1) {
      buffer.flip();
      out.write(buffer);
      buffer.clear();
    }
  }
Exemplo n.º 3
0
 /**
  * Write all remaining bytes in buffer to the given channel. If the channel is selectable then it
  * must be configured blocking.
  */
 private static void writeFullyImpl(WritableByteChannel ch, ByteBuffer bb) throws IOException {
   while (bb.remaining() > 0) {
     int n = ch.write(bb);
     if (n <= 0) throw new RuntimeException("no bytes written");
   }
 }