Ejemplo n.º 1
0
  public void writeResponsePacket(SocketChannel socketChannel, ResponsePacket responsePacket) {
    try {
      ByteBuffer byteBuffer;
      byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);

      byte[] marshalObject = MarshalHelper.objectToBytes(responsePacket);
      byte[] marshalHeader = MarshalHelper.int32ToBytes(marshalObject.length);
      byteBuffer.clear();
      byteBuffer.put(marshalHeader);
      byteBuffer.put(marshalObject);
      byteBuffer.flip();

      // If no connection now, please ignore it (usually in async calling)
      try {
        if (socketChannel.isConnected()) {
          socketChannel.write(byteBuffer);
        }
      } catch (IOException e) {
        socketChannel.close();
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 2
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);
    }
  }