Example usage for java.net MulticastSocket joinGroup

List of usage examples for java.net MulticastSocket joinGroup

Introduction

In this page you can find the example usage for java.net MulticastSocket joinGroup.

Prototype

public void joinGroup(InetAddress mcastaddr) throws IOException 

Source Link

Document

Joins a multicast group.

Usage

From source file:com.lfv.yada.net.client.ClientNetworkManager.java

public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr,
        SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL,
        TerminalProperties properties) throws IOException {

    // Create a logger for this class
    log = LogFactory.getLog(getClass());

    // Load terminal properties
    this.properties = properties;

    // Setup stuff
    this.terminalId = terminalId;
    this.bundle = bundle;
    this.serverSocketAddr = new SocketAddress(serverSocketAddr);

    // Resolve local host address
    InetAddress localHost = getLocalHostFix();
    if (localHost == null) {
        localHost = InetAddress.getLocalHost();
        if (localHost == null)
            throw new UnknownHostException("Could not resolve ip address of localhost");
    }// www  .  ja va2s  .  co  m

    // The socket to be used for sending and receiving unicast packets
    DatagramSocket usocket;
    if (localhostBindSocketAddr.getAddress() == 0)
        usocket = new DatagramSocket();
    else
        usocket = new DatagramSocket(localhostBindSocketAddr.getPort(),
                localhostBindSocketAddr.getInetAddress());

    // The multicast socket
    InetAddress maddr = multicastSocketAddr.getInetAddress();
    int mport = multicastSocketAddr.getPort();
    MulticastSocket msocket = null;

    multicastAvailable = (maddr != null && mport > 0);
    if (multicastAvailable) {
        msocket = new MulticastSocket(mport);
        try {
            msocket.joinGroup(maddr);
            msocket.setTimeToLive(multicastTTL);
        } catch (SocketException ex) {
            log.warn("!!!");
            log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!");
            log.warn("!!! On linux systems a default gateway must be defined, try:");
            log.warn("!!! > route add default gw <some_ip_address>");
            log.warn("!!!");
            msocket = null;
            multicastAvailable = false;
        }
    } else
        log.warn("No multicast address or port defined, multicasting has been disabled!");

    // Store the local unicast ip address and port
    localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort());

    // Create a receiver and a sender (send/recv must use the same port number)
    receiver = new ClientPacketReceiver(terminalId, usocket, msocket);
    sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling pings
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}

From source file:de.jaetzold.networking.SimpleServiceDiscovery.java

/**
 * Send a SSDP search message with the given search target (ST) and return a list of received responses.
 *//* w  ww  .ja v a  2 s.co  m*/
public Map<String, URL> discover(String searchTarget) {
    Log.d("HUE", "ServiceDiscovery.discover");
    final InetSocketAddress address;
    // standard multicast port for SSDP
    try {
        // multicast address with administrative scope
        address = new InetSocketAddress(InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
        //address = InetAddress.getByName(MULTICAST_ADDRESS);

    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not get multicast address", e);
    }

    final MulticastSocket socket;
    try {
        socket = new MulticastSocket(null);

        InetAddress localhost = getAndroidLocalIP();

        InetSocketAddress srcAddress = new InetSocketAddress(localhost, MULTICAST_PORT);
        Log.d("HUE", "" + srcAddress.getAddress());
        socket.bind(srcAddress);
        Log.d("HUE", "step 1");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not create multicast socket");
    }

    try {
        socket.setSoTimeout(socketTimeout);
        Log.d("HUE", "step 2");
    } catch (SocketException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set socket timeout", e);
    }

    try {
        socket.joinGroup(InetAddress.getByName(MULTICAST_ADDRESS));
        Log.d("HUE", "step 3");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not make multicast socket joinGroup " + address, e);
    }
    try {
        socket.setTimeToLive(ttl);
        Log.d("HUE", "step 4");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not set TTL " + ttl, e);
    }
    final byte[] transmitBuffer;
    try {
        transmitBuffer = constructSearchMessage(searchTarget).getBytes(CHARSET_NAME);
        Log.d("HUE", "step 5");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new IllegalStateException("WTF? " + CHARSET_NAME + " is not supported?", e);
    }
    DatagramPacket packet = null;
    try {
        packet = new DatagramPacket(transmitBuffer, transmitBuffer.length, address);
        Log.d("HUE", "step 6");
    } catch (SocketException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.send(packet);
        Log.d("HUE", "step 7");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Can not send search request", e);
    }
    Map<String, URL> result = new HashMap<String, URL>();
    byte[] receiveBuffer = new byte[1536];
    while (true) {
        try {
            Log.d("HUE", "sending packets");
            final DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length,
                    InetAddress.getByName(MULTICAST_ADDRESS), MULTICAST_PORT);
            socket.receive(receivePacket);
            //Log.d("HUE", new String(receivePacket.getData()));
            HueBridge response = parseResponsePacket(receivePacket);
            if (response != null) {
                Log.d("HUE", "resonse not null");
                ////System.out.println("resonse not null");
                result.put(response.getUDN(), response.getBaseUrl());
            } else {
                Log.d("HUE", "no bridge");
            }
        } catch (SocketTimeoutException e) {
            Log.e("HUE", "timeout exception");
            break;
        } catch (IOException e) {
            throw new IllegalStateException("Problem receiving search responses", e);
        }
    }
    return result;
}

From source file:net.pms.network.UPNPHelper.java

/**
 * Starts up two threads: one to broadcast UPnP ALIVE messages and another
 * to listen for responses. /*from   w w  w.j  av a 2 s . co m*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void listen() throws IOException {
    Runnable rAlive = new Runnable() {
        @Override
        public void run() {
            int delay = 10000;

            while (true) {
                sleep(delay);
                sendAlive();

                // The first delay for sending an ALIVE message is 10 seconds,
                // the second delay is for 20 seconds. From then on, all other
                // delays are for 180 seconds.
                switch (delay) {
                case 10000:
                    delay = 20000;
                    break;
                case 20000:
                    delay = 180000;
                    break;
                }
            }
        }
    };

    aliveThread = new Thread(rAlive, "UPNP-AliveMessageSender");
    aliveThread.start();

    Runnable r = new Runnable() {
        @Override
        public void run() {
            boolean bindErrorReported = false;

            while (true) {
                MulticastSocket multicastSocket = null;

                try {
                    // Use configurable source port as per http://code.google.com/p/ps3mediaserver/issues/detail?id=1166
                    multicastSocket = new MulticastSocket(configuration.getUpnpPort());

                    if (bindErrorReported) {
                        logger.warn(
                                "Finally, acquiring port " + configuration.getUpnpPort() + " was successful!");
                    }

                    NetworkInterface ni = NetworkConfiguration.getInstance().getNetworkInterfaceByServerName();

                    try {
                        // Setting the network interface will throw a SocketException on Mac OSX
                        // with Java 1.6.0_45 or higher, but if we don't do it some Windows
                        // configurations will not listen at all.
                        if (ni != null) {
                            multicastSocket.setNetworkInterface(ni);
                        } else if (PMS.get().getServer().getNetworkInterface() != null) {
                            multicastSocket.setNetworkInterface(PMS.get().getServer().getNetworkInterface());
                            logger.trace("Setting multicast network interface: "
                                    + PMS.get().getServer().getNetworkInterface());
                        }
                    } catch (SocketException e) {
                        // Not setting the network interface will work just fine on Mac OSX.
                    }

                    multicastSocket.setTimeToLive(4);
                    multicastSocket.setReuseAddress(true);
                    InetAddress upnpAddress = getUPNPAddress();
                    multicastSocket.joinGroup(upnpAddress);

                    while (true) {
                        byte[] buf = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
                        multicastSocket.receive(receivePacket);

                        String s = new String(receivePacket.getData());

                        InetAddress address = receivePacket.getAddress();

                        if (s.startsWith("M-SEARCH")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            if (configuration.getIpFiltering().allowed(address)) {
                                logger.trace(
                                        "Receiving a M-SEARCH from [" + remoteAddr + ":" + remotePort + "]");

                                if (StringUtils.indexOf(s,
                                        "urn:schemas-upnp-org:service:ContentDirectory:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:service:ContentDirectory:1");
                                }

                                if (StringUtils.indexOf(s, "upnp:rootdevice") > 0) {
                                    sendDiscover(remoteAddr, remotePort, "upnp:rootdevice");
                                }

                                if (StringUtils.indexOf(s, "urn:schemas-upnp-org:device:MediaServer:1") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, "ssdp:all") > 0) {
                                    sendDiscover(remoteAddr, remotePort,
                                            "urn:schemas-upnp-org:device:MediaServer:1");
                                }

                                if (StringUtils.indexOf(s, PMS.get().usn()) > 0) {
                                    sendDiscover(remoteAddr, remotePort, PMS.get().usn());
                                }
                            }
                        } else if (s.startsWith("NOTIFY")) {
                            String remoteAddr = address.getHostAddress();
                            int remotePort = receivePacket.getPort();

                            logger.trace("Receiving a NOTIFY from [" + remoteAddr + ":" + remotePort + "]");
                        }
                    }
                } catch (BindException e) {
                    if (!bindErrorReported) {
                        logger.error("Unable to bind to " + configuration.getUpnpPort()
                                + ", which means that PMS will not automatically appear on your renderer! "
                                + "This usually means that another program occupies the port. Please "
                                + "stop the other program and free up the port. "
                                + "PMS will keep trying to bind to it...[" + e.getMessage() + "]");
                    }

                    bindErrorReported = true;
                    sleep(5000);
                } catch (IOException e) {
                    logger.error("UPNP network exception", e);
                    sleep(1000);
                } finally {
                    if (multicastSocket != null) {
                        // Clean up the multicast socket nicely
                        try {
                            InetAddress upnpAddress = getUPNPAddress();
                            multicastSocket.leaveGroup(upnpAddress);
                        } catch (IOException e) {
                        }

                        multicastSocket.disconnect();
                        multicastSocket.close();
                    }
                }
            }
        }
    };

    listenerThread = new Thread(r, "UPNPHelper");
    listenerThread.start();
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Starts Multicast Discovery Service. This can only
 * be invoked by a Nebula ClusterManager.
 * /*from   w  ww. ja  v  a 2  s  .com*/
 * @throws IOException if occurred during operation
 * @throws UnsupportedOperationException if invoked by non-ClusterManager nodes.
 */
public static void startService() throws IOException, UnsupportedOperationException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    // Start Service
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {

                // Start Multicast Socket and listen for Requests
                final MulticastSocket mSock = new MulticastSocket(SERVICE_PORT);
                mSock.joinGroup(SERVICE_REQUEST_IP);

                // Infinite Loop
                while (true) {
                    // Buffer (for Greeting Message)
                    byte[] msg = new byte[GREET_MSG.getBytes("UTF-8").length];

                    // Create Datagram Packet
                    DatagramPacket packet = new DatagramPacket(msg, msg.length);

                    // Wait and Receive Request
                    mSock.receive(packet);
                    log.debug("[MulticastDiscovery] Received Discovery Request");

                    // Check if Greeting Message is valid
                    try {
                        String greet = new String(packet.getData());
                        if (!greet.equals(GREET_MSG)) {
                            throw new IllegalArgumentException("Invalid Greeting");
                        }
                    } catch (Exception e) {
                        log.debug("Malformed Multicast Message Igonored");
                        continue;
                    }

                    // Respond
                    doRespond();
                }

            } catch (IOException e) {
                log.error("[MulticastDiscovery] Service Failed on Receive", e);
            }

        }

    });
    t.setDaemon(true); // Run as Daemon thread
    t.start(); // Start Service
    log.debug("[MulticastDiscovery] Service Started");
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Discovery Process to identify Clusters with in 
 * network.// w w w .  ja v a 2s .c o m
 * 
 * @throws IOException if occurred during operation
 */
private void doDiscover() throws IOException {

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Wait for Response
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Receive
    resSock.setSoTimeout((int) TIMEOUT);
    try {
        resSock.receive(response);
    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    }

    byte[] data = response.getData();

    byte[] ipBytes = Arrays.copyOfRange(data, 0, 4);
    byte[] portBytes = Arrays.copyOfRange(data, 4, 9);

    InetAddress ip = InetAddress.getByAddress(ipBytes);
    StringBuilder sb = new StringBuilder(ip.getHostAddress());
    sb.append(":");
    for (byte b : portBytes) {
        sb.append(b);
    }

    this.cluster = sb.toString();
}

From source file:org.nebulaframework.discovery.multicast.MulticastDiscovery.java

/**
 * Attempts to discover peer clusters using Multicast
 * Discovery. Each discovered Cluster will be notified
 * to the {@code PeerClusterService} of the 
 * ClusterManager.//from   w  w  w  .j  a v  a 2s  .  c  om
 * 
 * @throws IOException if occurred during process
 */
public static void discoverPeerClusters() throws IOException {

    // Only allowed for ClusterManagers
    if (!Grid.isClusterManager()) {
        throw new UnsupportedOperationException(
                "Multicast Discovery Service can be enabled only for ClusterManagers");
    }

    log.info("[MulticastDiscovery] Discovering Peer Clusters...");

    // Send Request
    byte[] greet = GREET_MSG.getBytes("UTF-8");
    DatagramPacket request = new DatagramPacket(greet, greet.length, SERVICE_REQUEST_IP, SERVICE_PORT);
    MulticastSocket reqSock = new MulticastSocket();
    reqSock.send(request);

    // Response Socket
    MulticastSocket resSock = new MulticastSocket(SERVICE_PORT);
    resSock.joinGroup(SERVICE_RESPONSE_IP);

    // 9 = # of bytes for an IP Address + 5 byte port
    DatagramPacket response = new DatagramPacket(new byte[9], 9);

    // Set Socket Timeout
    resSock.setSoTimeout((int) TIMEOUT);

    try {

        // Loop until Socket Timeout Occurs
        while (true) {

            // Receive
            resSock.receive(response);
            processPeerResponse(response.getData());

        }

    } catch (SocketTimeoutException e) {
        log.debug("[MulticastDiscovery] Receive Timeout");
        return;
    } finally {
        log.info("[MulticastDiscovery] Peer Cluster Discovery Complete");
    }

}

From source file:org.openhab.binding.hue.internal.tools.SsdpDiscovery.java

/**
 * Broadcasts a SSDP discovery message into the network to find provided
 * services.//w  w  w. java2 s .com
 * 
 * @return The Socket the answers will arrive at.
 * @throws UnknownHostException
 * @throws IOException
 * @throws SocketException
 * @throws UnsupportedEncodingException
 */
private MulticastSocket sendDiscoveryBroacast()
        throws UnknownHostException, IOException, SocketException, UnsupportedEncodingException {
    InetAddress multicastAddress = InetAddress.getByName("239.255.255.250");
    final int port = 1900;
    MulticastSocket socket = new MulticastSocket(port);
    socket.setReuseAddress(true);
    socket.setSoTimeout(130000);
    socket.joinGroup(multicastAddress);
    byte[] requestMessage = DISCOVER_MESSAGE.getBytes("UTF-8");
    DatagramPacket datagramPacket = new DatagramPacket(requestMessage, requestMessage.length, multicastAddress,
            port);
    socket.send(datagramPacket);
    return socket;
}

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

@Test
public void verifySendMulticast() throws Exception {
    MulticastSocket socket;//from  w  ww . j  av a 2s  .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.DatagramPacketMulticastSendingHandlerTests.java

@Test
public void verifySendMulticastWithAcks() throws Exception {

    MulticastSocket socket;/*from   w w  w  .j ava 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();
}

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

@Test
@Ignore/*  w  ww  . j  a  v  a 2 s .c  o 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();
}