Example #1
0
  private void onReadRequests(SocketChannel socketChannel) throws IOException {
    ByteBuffer byteBuffer;
    byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);

    byteBuffer.clear();
    socketChannel.read(byteBuffer);
    byteBuffer.flip();

    int countBytes = byteBuffer.limit();
    if (countBytes == 0) {
      socketChannel.close();
    }

    int cursor = 0;

    // System.out.println(countBytes);

    while (cursor < countBytes) {
      // TODO: Not considered with slitted packet!
      byte[] marshallBytes = readBytes(socketChannel, byteBuffer, 4);
      int packetLength = MarshalHelper.bytesToInt32(marshallBytes);

      byte[] marshallObject = readBytes(socketChannel, byteBuffer, packetLength);
      cursor += Integer.BYTES + packetLength;

      RequestPacket requestPacket = null;

      try {
        requestPacket = (RequestPacket) MarshalHelper.byteToObject(marshallObject);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }

      dispatchRequestPacket(socketChannel, requestPacket);
    }
  }