Ejemplo n.º 1
0
  public static void main(final String[] args) throws IOException {
    final FileChannel receiveFileChannel = Common.createTmpFileChannel();
    final ByteBuffer receiveByteBuffer =
        receiveFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel receiveDatagramChannel = DatagramChannel.open();
    init(receiveDatagramChannel);
    receiveDatagramChannel.bind(new InetSocketAddress("localhost", 40124));
    receiveDatagramChannel.connect(new InetSocketAddress("localhost", 40123));

    final FileChannel sendFileChannel = Common.createTmpFileChannel();
    final ByteBuffer sendByteBuffer =
        sendFileChannel.map(FileChannel.MapMode.READ_WRITE, 0, MTU_LENGTH_DEFAULT);
    final DatagramChannel sendDatagramChannel = DatagramChannel.open();
    init(sendDatagramChannel);
    sendDatagramChannel.bind(new InetSocketAddress("localhost", 40125));
    sendDatagramChannel.connect(new InetSocketAddress("localhost", 40126));

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    final int packetSize = SIZE_OF_LONG * 2;

    while (true) {
      boolean available = false;
      while (!available) {
        if (!running.get()) {
          return;
        }

        final long bytesReceived =
            receiveFileChannel.transferFrom(receiveDatagramChannel, 0, packetSize);
        if (packetSize == bytesReceived) {
          available = true;
        }
      }

      final long receivedSequenceNumber = receiveByteBuffer.getLong(0);
      final long receivedTimestamp = receiveByteBuffer.getLong(SIZE_OF_LONG);

      sendByteBuffer.putLong(0, receivedSequenceNumber);
      sendByteBuffer.putLong(SIZE_OF_LONG, receivedTimestamp);

      final long bytesSent = sendFileChannel.transferTo(0, packetSize, sendDatagramChannel);
      if (packetSize != bytesSent) {
        throw new IllegalStateException("Invalid bytes sent " + bytesSent);
      }
    }
  }