Пример #1
0
  private void write(SelectionKey key) throws IOException {
    SocketChannel ch = (SocketChannel) key.channel();
    int count = 0;

    synchronized (pendingData) {
      List queue = (List) pendingData.get(ch);
      /**
       * Null exception alert: This can happen once a connection was established. Check send() for
       * more information.
       */
      if (queue == null) return;

      while (!queue.isEmpty()) {
        ByteBuffer buf = (ByteBuffer) queue.get(0);
        ch.write(buf);

        count += buf.capacity() - buf.remaining();
        if (buf.remaining() > 0) break;
        queue.remove(0);
      }

      if (queue.isEmpty()) key.interestOps(SelectionKey.OP_READ);
    }

    if (!listener.handleWrite(ch, count)) close(ch);
  }
Пример #2
0
  private void read(SelectionKey key) throws IOException {
    SocketChannel ch = (SocketChannel) key.channel();

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    int count;
    try {
      count = ch.read(buffer);
    } catch (IOException e) {
      close(ch);
      return;
    }

    buffer.flip();
    if (count == -1 || (listener != null && !listener.handleRead(ch, buffer, count))) close(ch);
  }