Example usage for java.net DatagramPacket getLength

List of usage examples for java.net DatagramPacket getLength

Introduction

In this page you can find the example usage for java.net DatagramPacket getLength.

Prototype

public synchronized int getLength() 

Source Link

Document

Returns the length of the data to be sent or the length of the data received.

Usage

From source file:org.jopenray.client.RendererListener.java

public void start() {
    Thread t = new Thread(new Runnable() {

        @Override//w  w  w .j a v  a  2  s  . com
        public void run() {
            connectionDate = System.currentTimeMillis();
            DatagramPacket data = new DatagramPacket(udpData, udpData.length);
            try {
                while (true) {
                    System.out.println("Listening on port:" + port);
                    socket.receive(data);
                    dataLength = data.getLength();
                    handlePacket();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    });
    t.start();
}

From source file:br.com.skylane.voicer.rtp.RtpMediaDecoder.java

@Override
public void processDatagramPacket(DatagramPacket pct) {
    if (playerThread == null || decoder == null)
        return;//from ww  w.j av  a2s  . c o  m

    ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(pct.getData(), 0, pct.getLength());
    DataPacket dp = DataPacket.decode(buffer);
    dp.setTimestamp(dp.getTimestamp() * 1000L / 90L);

    if (lastSequenceNumberIsValid && (lastSequenceNumber + 1) != dp.getSequenceNumber()) {
        lastSequenceNumber = dp.getSequenceNumber();
        return; // droppack
    }

    H264Packet h264Packet = new H264Packet(dp);

    if (!decoderInicializado && !h264Packet.h264NalType.equals(NalType.STAPA))
        return;

    switch (h264Packet.h264NalType) {
    case FULL:
        inputBufIndex = decoder.dequeueInputBuffer(-1);
        inputBuf = inputBuffers[inputBufIndex];
        inputBuf.clear();
        inputBuf.put(dp.getDataAsArray());

        playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 1, inputBufIndex);
        break;
    case FUA:
        if (h264Packet.isStart()) {
            if (RtpMediaDecoder.DEBUGGING) {
                log.info("FU-A start found. Starting new frame");
            }

            inputBufIndex = decoder.dequeueInputBuffer(-1);
            inputBuf = inputBuffers[inputBufIndex];
            inputBuf.clear();

            currentTimestamp = dp.getTimestamp();
        }

        // if we don't have a buffer here, it means that we skipped the start packet for this
        // NAL unit, so we can't do anything other than discard everything else
        if (currentTimestamp != 0) {

            // Did we miss packets in the middle of a frame transition?
            // In that case, I don't think there's much we can do other than flush our buffer
            // and discard everything until the next buffer
            if (dp.getTimestamp() != currentTimestamp) {
                if (RtpMediaDecoder.DEBUGGING) {
                    log.warn("Non-consecutive timestamp found");
                }
            } else {

                inputBuf.put(dp.getDataAsArray(), 2, dp.getDataSize() - 2);

            }

            if (h264Packet.isEnd()) {
                if (RtpMediaDecoder.DEBUGGING) {
                    log.info("FU-A end found. Sending frame!");
                }

                playerThread.decodeFrame(inputBuf, currentTimestamp, 0, inputBufIndex);

                currentTimestamp = 0;

            }
        }
        break;
    case STAPA:

        decoderInicializado = true;

        inputBufIndex = decoder.dequeueInputBuffer(-1);
        inputBuf = inputBuffers[inputBufIndex];
        inputBuf.clear();

        int idx = VoicerHelper.indexOf(dp.getDataAsArray(), new byte[] { 0, 0, 0, 1 }, 4);

        inputBuf.put(dp.getDataAsArray(), 1, idx - 1);

        playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 0, inputBufIndex);

        inputBufIndex = decoder.dequeueInputBuffer(-1);
        inputBuf = inputBuffers[inputBufIndex];
        inputBuf.clear();

        inputBuf.put(dp.getDataAsArray(), idx, dp.getDataSize() - idx);

        playerThread.decodeFrame(inputBuf, dp.getTimestamp(), 0, inputBufIndex);

        break;
    case UNKNOWN:
        break;
    default:
        break;
    }

    lastSequenceNumber = dp.getSequenceNumber();
    lastSequenceNumberIsValid = true;

    /*android.util.Log.d("VOICER", new String("<< Received: " + pct.getLength()));
    android.util.Log.d("VOICER", "<< HEX " + VoicerHelper.converteDadosBinariosParaStringHexa(dp.getDataAsArray()));
    android.util.Log.d("VOICER", "<< Sequence # " + dp.getSequenceNumber());*/

    /*String str = "";
    for (int i=0; i<pct.getLength(); i++)
       str+=pct.getData()[i] + ":";
    */
    //android.util.Log.d(VoicerHelper.TAG, "<< #" + dp.getSequenceNumber() + " length " + dp.getDataSize());

}

From source file:com.bitbreeds.webrtc.datachannel.DataChannelImpl.java

@Override
public void run() {
    if (parent.getRemote() == null) {
        throw new IllegalArgumentException("No user data set for remote user");
    }/* w  ww.ja  v  a 2s. c  om*/

    logger.info("Started listening to port: " + port);
    while (running && channel.isBound()) {

        byte[] bt = new byte[bufferSize];

        try {
            if (mode == ConnectionMode.BINDING) {
                logger.info("Listening for binding on: " + channel.getLocalSocketAddress() + " - "
                        + channel.getPort());
                Thread.sleep(5); //No reason to hammer on this

                DatagramPacket packet = new DatagramPacket(bt, 0, bt.length);
                channel.receive(packet);
                SocketAddress currentSender = packet.getSocketAddress();

                sender = currentSender;
                byte[] data = Arrays.copyOf(packet.getData(), packet.getLength());
                logger.info("Received data: " + Hex.encodeHexString(data) + " on "
                        + channel.getLocalSocketAddress() + " - " + channel.getPort());

                byte[] out = bindingService.processBindingRequest(data, parent.getLocal().getUserName(),
                        parent.getLocal().getPassword(), (InetSocketAddress) currentSender);

                ByteBuffer outData = ByteBuffer.wrap(out);
                logger.info("Sending: " + Hex.encodeHexString(outData.array()) + " to " + currentSender);

                DatagramPacket pc = new DatagramPacket(out, 0, out.length);
                pc.setSocketAddress(sender);
                channel.send(pc);

                this.mode = ConnectionMode.HANDSHAKE; //Go to handshake mode
                logger.info("-> DTLS handshake");
            } else if (mode == ConnectionMode.HANDSHAKE) {
                Thread.sleep(5);
                logger.info("In handshake mode: ");

                if (transport == null) {
                    channel.connect(sender);

                    /**
                     * {@link NioUdpTransport} might replace the {@link UDPTransport} here.
                     * @see <a href="https://github.com/RestComm/mediaserver/blob/master/io/rtp/src/main/java/org/mobicents/media/server/impl/srtp/NioUdpTransport.java">NioUdpTransport</a>
                     */
                    transport = serverProtocol.accept(dtlsServer,
                            new DtlsMuxStunTransport(parent, channel, MTU));
                }

                sctpService = new SCTPImpl(this);

                mode = ConnectionMode.TRANSFER;
                logger.info("-> SCTP mode");
            } else if (mode == ConnectionMode.TRANSFER) {

                /**
                 * Here we receive message and put them to a worker thread for handling
                 * If the output of handling the message is a message, then we send those
                 * using the same thread.
                 */
                byte[] buf = new byte[transport.getReceiveLimit()];
                int length = transport.receive(buf, 0, buf.length, waitMillis);
                if (length >= 0) {
                    byte[] handled = Arrays.copyOf(buf, length);
                    workPool.submit(() -> {
                        try {
                            List<byte[]> data = sctpService.handleRequest(handled);
                            data.forEach(this::putDataOnWire);
                        } catch (Exception e) {
                            logger.error("Failed handling message: ", e);
                        }
                    });
                    logger.debug("Input: " + Hex.encodeHexString(handled));
                }
            }
        } catch (Exception e) {
            logger.error("Com error:", e);
            logger.info("Shutting down, we cannot continue here");
            running = false; //Need to quit channel now
        }
    }
    workPool.shutdown();
}

From source file:org.avineas.fins.gw.Gateway.java

/**
 * The after properties set method of this gateway. The method initializes
 * a new thread that continuously reads from the UDP port for getting data
 * for local (or remote) nodes. This method <b>must</b> be called before
 * actual receiving of data can take place.
 *//* www  .j  a va 2s . c  o  m*/
@PostConstruct
public void init() throws SocketException {
    if (thread != null)
        return;
    if (channel == null)
        setPort(9600);

    // Initialize the nodes and handling of the packets.
    thread = new Thread() {
        @SuppressWarnings("synthetic-access")
        @Override
        public void run() {
            byte[] data = new byte[Frame.MAXFRAMESIZE];
            logger.info(Gateway.this + " started");
            for (;;) {
                try {
                    // Read a datagram from the network
                    DatagramPacket dpacket = new DatagramPacket(data, 0, data.length);
                    channel.receive(dpacket);

                    // Update the FINS node/gateway information
                    Destination dest = new Destination(dpacket.getAddress(), dpacket.getPort());
                    traceDatagram(dest + " -> " + channel.getLocalPort(), dpacket);
                    Frame packet = new Frame(data, dpacket.getLength());
                    Address from = packet.getSource();
                    setDestination(from.getNodeAsString(), dest);

                    // Handle the packet. It is either forwarded to
                    // a remote machine or locally handled. 
                    // Note that there is a possibility that gateways keep
                    // each other busy with sending data to each other. This
                    // cannot be prevented here.
                    Address to = packet.getDestination();
                    NodeUnit unit = units.get(to.toString());
                    if (unit != null) {
                        logger.info("received " + (packet.isReply() ? "reply" : "packet") + " frame from: "
                                + dest + ", for local unit: " + to + " from: " + packet.getSource());
                        Frame reply = unit.handleFrame(packet);
                        if (reply != null)
                            send(reply);
                    } else {
                        logger.info("frame for node " + to + " cannot be handled locally, trying forward");
                        send(packet);
                    }
                } catch (Exception exc) {
                    if (!runDown) {
                        synchronized (this) {
                            // Will normally only occur when the port is changed on the fly
                            logger.error("exception handling frame", exc);
                        }
                    }
                }
                // In case we were shut down, stop
                if (runDown)
                    break;
            }
            logger.info("FINS gateway shutdown complete");
        }
    };
    thread.start();
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
@Ignore//  w  ww. j  av a 2s . co m
public void verifySendMulticast() throws Exception {
    final int testPort = SocketUtils.findAvailableUdpSocket();
    final String multicastAddress = "225.6.7.8";
    final String payload = "foo";
    final CountDownLatch latch1 = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    Runnable catcher = new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[8];
                DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
                MulticastSocket socket = new MulticastSocket(testPort);
                InetAddress group = InetAddress.getByName(multicastAddress);
                socket.joinGroup(group);
                latch1.countDown();
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
                socket.receive(receivedPacket);
                socket.close();
                byte[] src = receivedPacket.getData();
                int length = receivedPacket.getLength();
                int offset = receivedPacket.getOffset();
                byte[] dest = new byte[length];
                System.arraycopy(src, offset, dest, 0, length);
                assertEquals(payload, new String(dest));
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
                latch2.countDown();
            } catch (Exception e) {
                noMulticast = true;
                latch1.countDown();
                e.printStackTrace();
            }
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    latch1.await(3000, TimeUnit.MILLISECONDS);
    if (noMulticast) {
        return;
    }
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(3000, TimeUnit.MILLISECONDS));
    handler.shutDown();
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;//  ww w  .  j  a v a  2  s  .  c om
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final String multicastAddress = this.multicastRule.getGroup();
    final String payload = "foo";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch received = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[8];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[length];
            System.arraycopy(src, offset, dest, 0, length);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            received.countDown();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.afterPropertiesSet();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(received.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}

From source file:org.springframework.integration.ip.udp.DatagramPacketSendingHandlerTests.java

@Test
@Ignore//from   www .j a  v  a  2s  . c o  m
public void verifySendMulticastWithAcks() throws Exception {

    final List<Integer> openPorts = SocketUtils.findAvailableUdpSockets(SocketUtils.getRandomSeedPort(), 2);

    final int testPort = openPorts.get(0);
    final int ackPort = openPorts.get(1);

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch latch1 = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    Runnable catcher = new Runnable() {
        public void run() {
            try {
                byte[] buffer = new byte[1000];
                DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
                MulticastSocket socket = new MulticastSocket(testPort);
                InetAddress group = InetAddress.getByName(multicastAddress);
                socket.joinGroup(group);
                latch1.countDown();
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
                socket.receive(receivedPacket);
                socket.close();
                byte[] src = receivedPacket.getData();
                int length = receivedPacket.getLength();
                int offset = receivedPacket.getOffset();
                byte[] dest = new byte[6];
                System.arraycopy(src, offset + length - 6, dest, 0, 6);
                assertEquals(payload, new String(dest));
                LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
                DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
                mapper.setAcknowledge(true);
                mapper.setLengthCheck(true);
                Message<byte[]> message = mapper.toMessage(receivedPacket);
                Object id = message.getHeaders().get(IpHeaders.ACK_ID);
                byte[] ack = id.toString().getBytes();
                DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                        new InetSocketAddress("localHost", ackPort));
                DatagramSocket out = new DatagramSocket();
                out.send(ackPack);
                out.close();
                latch2.countDown();
            } catch (Exception e) {
                noMulticast = true;
                latch1.countDown();
                e.printStackTrace();
            }
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    latch1.await(3000, TimeUnit.MILLISECONDS);
    if (noMulticast) {
        return;
    }
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", ackPort, 500000);
    handler.setMinAcksForSuccess(2);
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(latch2.await(10000, TimeUnit.MILLISECONDS));
    handler.shutDown();
}

From source file:udpserver.UDPui.java

private void receiveUDP() {
    countSeparate = new ArrayList<>();
    background = new Runnable() {
        public void run() {
            try {
                serverSocket = new DatagramSocket(9876);
            } catch (SocketException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            }//from w  w w.  jav  a  2  s  . c o m
            //                while (true) {
            //                    byte[] receiveData = new byte[1024];
            //                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            //<editor-fold defaultstate="collapsed" desc="Start timer after receive a packet">
            //                    try {
            //                        serverSocket.receive(receivePacket);
            //                        series.clear();
            //                        valuePane.setText("");
            available = true;
            //                        System.out.println(available);
            //                    } catch (IOException ex) {
            //                        Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
            //                    }

            //                    Timer timer = new Timer();
            //                    timer.schedule(new TimerTask() {
            //                        @Override
            //                        public void run() {
            //                            available = false;
            //                            System.out.println("Finish Timer");
            //                        }
            //                    }, 1 * 1000);
            //</editor-fold>
            //                    if (!new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()).equals("")) {
            //                        int count = 1;
            //                        while (available) {
            while (true) {
                try {
                    byte[] receiveData = new byte[total_byte];
                    byte[] sendData = new byte[32];
                    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                    serverSocket.receive(receivePacket);

                    String word = receivePacket.getAddress().getHostAddress();
                    System.out.println(word);

                    String message = new String(receivePacket.getData(), receivePacket.getOffset(),
                            receivePacket.getLength());
                    boolean looprun = true;

                    //                                System.out.println(message);
                    while (looprun) {
                        Integer countt = counting.get(word);
                        if (message.contains("&")) {
                            message = message.substring(message.indexOf("&") + 1);
                            //                                        count++;
                            //                                        Integer countt = counting.get(word);
                            if (countt == null) {
                                counting.put(word, 1);
                            } else {
                                counting.put(word, countt + 1);
                            }
                            //                                        System.out.println(count + ":" + message);
                        } else {
                            if (countt == null) {
                                counting.put(word, 1);
                            } else {
                                counting.put(word, countt + 1);
                            }
                            System.out.println(counting.get(word));
                            looprun = false;
                        }
                    }

                    if (message.contains("start")) {
                        if (counting.get(word) != null) {
                            counting.remove(word);
                        }
                    } else if (message.contains("end")) {
                        message = message.substring(message.indexOf("end") + 3);
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //send back to mobile
                        InetAddress IPAddress = receivePacket.getAddress();
                        int port = receivePacket.getPort();
                        //                                    String capitalizedSentence = count + "";

                        String capitalizedSentence = counting.get(word) + "";
                        sendData = capitalizedSentence.getBytes();
                        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
                                port);
                        serverSocket.send(sendPacket);

                        String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss")
                                .format(Calendar.getInstance().getTime());
                        String content = IPAddress.getCanonicalHostName() + "," + timeStamp + ","
                                + (counting.get(word) - 1) + "," + message;
                        saveFile(content);
                        //end send back to mobile
                        //                                    System.out.println(counting.get(word));
                        //                                    count = 1;
                        counting.remove(word);
                        //                                    break;
                    } else if (available) {

                        //<editor-fold defaultstate="collapsed" desc="check hasmap key">
                        //                                    if (hm.size() > 0 && hm.containsKey(serverSocket.getInetAddress().getHostAddress())) {
                        //                                        hm.put(foundKey, new Integer(((int) hm.get(foundKey)) + 1));
                        //                                        hm.put(serverSocket.getInetAddress().getHostAddress(), new Integer(((int) hm.get(serverSocket.getInetAddress().getHostAddress())) + 1));
                        //                                    } else {
                        //                                        hm.put(serverSocket.getInetAddress().getHostAddress(), 1);
                        //                                        hm.entrySet().add(new Map<String, Integer>.Entry<String, Integer>());
                        //                                    }
                        //</editor-fold>
                        //                                    series.add(count, Double.parseDouble(message));
                        //                                    valuePane.setText(valuePane.getText().toString() + count + ":" + message + "\n");
                        //                                    valuePane.setCaretPosition(valuePane.getDocument().getLength());
                        //                                    count++;
                    }
                } catch (IOException ex) {
                    Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                    valuePane.setText(valuePane.getText().toString() + "IOException" + "\n");
                }
            }
            //                        valuePane.setText(valuePane.getText().toString() + "Out of while loop" + "\n");
            //                    }
            //                }
        }

        private void saveFile(String content) {
            try {
                File desktop = new File(System.getProperty("user.home"), "Desktop");
                File file = new File(desktop.getAbsoluteFile() + "/udp.csv");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream fop = new FileOutputStream(file, true);
                fop.write((content + "\n").getBytes());
                fop.flush();
                fop.close();
                //                    String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(Calendar.getInstance().getTime());
                //                    valuePane.setText(valuePane.getText().toString() + timeStamp + "\n");
            } catch (IOException ex) {
                Logger.getLogger(UDPui.class.getName()).log(Level.SEVERE, null, ex);
                String timeStamp = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss")
                        .format(Calendar.getInstance().getTime());
                valuePane.setText(valuePane.getText().toString() + timeStamp + "\n");
            }
        }
    };
    backgroundProcess = new Thread(background);
}

From source file:Reflector.java

private void listen(DatagramSocket ds) {
    // loop forever listening to packets, when they
    // arrive log them and notify all interested threads.

    byte[] buffer;
    DatagramPacket packet;

    while (true) {
        try {//w  w w. java  2s  .c om
            buffer = new byte[MAX_PACKET_SIZE];
            packet = new DatagramPacket(buffer, buffer.length);

            ds.receive(packet);

            logger.log("Packet received, " + packet.getLength() + " bytes");
            eventNotify(packet);

        } catch (IOException e) {
            System.err.println("Error receiving packet\n");
            e.printStackTrace();
        }
    }
}

From source file:org.springframework.integration.ip.udp.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/*from  w w  w  .ja va 2s.c o m*/
    try {
        socket = new MulticastSocket();
    } catch (Exception e) {
        return;
    }
    final int testPort = socket.getLocalPort();
    final AtomicInteger ackPort = new AtomicInteger();

    final String multicastAddress = "225.6.7.8";
    final String payload = "foobar";
    final CountDownLatch listening = new CountDownLatch(2);
    final CountDownLatch ackListening = new CountDownLatch(1);
    final CountDownLatch ackSent = new CountDownLatch(2);
    Runnable catcher = () -> {
        try {
            byte[] buffer = new byte[1000];
            DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length);
            MulticastSocket socket1 = new MulticastSocket(testPort);
            socket1.setInterface(InetAddress.getByName(multicastRule.getNic()));
            socket1.setSoTimeout(8000);
            InetAddress group = InetAddress.getByName(multicastAddress);
            socket1.joinGroup(group);
            listening.countDown();
            assertTrue(ackListening.await(10, TimeUnit.SECONDS));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " waiting for packet");
            socket1.receive(receivedPacket);
            socket1.close();
            byte[] src = receivedPacket.getData();
            int length = receivedPacket.getLength();
            int offset = receivedPacket.getOffset();
            byte[] dest = new byte[6];
            System.arraycopy(src, offset + length - 6, dest, 0, 6);
            assertEquals(payload, new String(dest));
            LogFactory.getLog(getClass()).debug(Thread.currentThread().getName() + " received packet");
            DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper();
            mapper.setAcknowledge(true);
            mapper.setLengthCheck(true);
            Message<byte[]> message = mapper.toMessage(receivedPacket);
            Object id = message.getHeaders().get(IpHeaders.ACK_ID);
            byte[] ack = id.toString().getBytes();
            DatagramPacket ackPack = new DatagramPacket(ack, ack.length,
                    new InetSocketAddress(multicastRule.getNic(), ackPort.get()));
            DatagramSocket out = new DatagramSocket();
            out.send(ackPack);
            LogFactory.getLog(getClass())
                    .debug(Thread.currentThread().getName() + " sent ack to " + ackPack.getSocketAddress());
            out.close();
            ackSent.countDown();
            socket1.close();
        } catch (Exception e) {
            listening.countDown();
            e.printStackTrace();
        }
    };
    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(catcher);
    executor.execute(catcher);
    assertTrue(listening.await(10000, TimeUnit.MILLISECONDS));
    MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort,
            true, true, "localhost", 0, 10000);
    handler.setLocalAddress(this.multicastRule.getNic());
    handler.setMinAcksForSuccess(2);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    waitAckListening(handler);
    ackPort.set(handler.getAckPort());
    ackListening.countDown();
    handler.handleMessage(MessageBuilder.withPayload(payload).build());
    assertTrue(ackSent.await(10000, TimeUnit.MILLISECONDS));
    handler.stop();
    socket.close();
}