Пример #1
0
  private void write(SelectionKey key) {
    SocketChannel socketChannel = (SocketChannel) key.channel();

    DataServerMessage sendMessage = mSendingData.get(socketChannel);

    boolean closeChannel = false;
    try {
      sendMessage.send(socketChannel);
    } catch (IOException e) {
      closeChannel = true;
      LOG.error(e.getMessage());
    }

    if (sendMessage.finishSending() || closeChannel) {
      try {
        key.channel().close();
      } catch (IOException e) {
        LOG.error(e.getMessage());
      }
      key.cancel();
      mReceivingData.remove(socketChannel);
      mSendingData.remove(socketChannel);
      sendMessage.close();
      mBlocksLocker.unlock(Math.abs(sendMessage.getBlockId()), sendMessage.getLockId());
    }
  }
 /**
  * Create a new socket to the data port and send a block request. The returned value is the
  * response from the server.
  */
 private DataServerMessage request(final BlockInfo block, final long offset, final long length)
     throws IOException, TException {
   DataServerMessage sendMsg =
       DataServerMessage.createBlockRequestMessage(block.blockId, offset, length);
   SocketChannel socketChannel =
       SocketChannel.open(
           new InetSocketAddress(
               block.getLocations().get(0).getWorkerAddress().getHost(),
               block.getLocations().get(0).getWorkerAddress().getDataPort()));
   try {
     while (!sendMsg.finishSending()) {
       sendMsg.send(socketChannel);
     }
     DataServerMessage recvMsg =
         DataServerMessage.createBlockResponseMessage(false, block.blockId, offset, length, null);
     while (!recvMsg.isMessageReady()) {
       int numRead = recvMsg.recv(socketChannel);
       if (numRead == -1) {
         break;
       }
     }
     return recvMsg;
   } finally {
     socketChannel.close();
   }
 }